vue中$bus的用法及$emit、$on、$off的使用

本文介绍Vue.js中使用$bus实现非父子组件间通信的方法,包括$emit触发事件、$on监听事件及$off解绑事件的具体应用。

vue中 $bus 一般与 $emit、 $on、 $off 连用,一般用在任意组件间的通信,即 $bus 用来传递非父子关系的数据。
如两个组件之间传递数据:
子组件1

this.$bus.$emit("hello",param);

子组件2

this.$bus.$on("hello",(param)=>{
});

1、$emit

  • $emit(‘自定义事件名’,要传递的数据);
  • 触发当前实例上的自定义事件,要传递的数据会传给监听器;

2、$on

  • $on(‘自定义事件名’,callback);
  • 监听当前实例上自定义事件,callback回调$emit要传递的数据;

注意:$emit 和 $on 的事件必须在一个公共的实例上,才能够触发。

3、实例事件
实例事件就是在构造器外部调用构造器内部的数据。

4、实例
在Student组件中提供数据给另一个School组件

<template>
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
    </div>
</template>

<script>
    export default {
        name:'Student',
        data() {
            return {
                name:'曹操',
                sex:'男',
            }
        },
        methods: {
        	//提供发送数据
            sendStudentName(){        
                this.$bus.$emit('hello',this.name)
            }
        },
    }
</script>

在School组件中使用事件总线,接收数据。School组件想接收数据,则在School组件中给 $bus绑定事件,事件的回调则留在School组件自身。

<template>
    <div class="school">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>

<script>
    export default {
        name:'School',
        data() {
            return {
                name:'交通学院',
                address:'上海',
            }
        },
        mounted() {
        	//绑定当前事件(这里以hello为例)
            this.$bus.$on('hello',(data)=>{      
                console.log('我是School组件,收到了数据',data)
            })
        },
        //收尾操作,销毁
        beforeDestroy(){        
            this.$bus.$off('hello')  //$off解绑当前组件所用到的事件
        }
    }
</script>

其中,$off 解绑当前组件所用到的事件。

5、小结
$emit写在子组件 / 兄弟组件:

  methods: {
	bgClick() {
	      bus.$emit('getMsg1')
		  bus.$emit('setIndex1')
	 },
    ...
  },

$on写在父组件 / 兄弟组件:

  mounted() {
    bus.$on('getMsg1', this.getMsg);
    bus.$on('setIndex1', this.setIndex);
  },
  beforeDestroy() {
    bus.$off('getMsg1');
    bus.$off('setIndex1');
  },
### Vue 中 `this.$bus.$on` 的使用方法 在 Vue 应用中,`this.$bus.$on` 用于监听全局事件总线上的自定义事件。这种技术常被用来实现非父子组件之间的通信,尤其是在跨层级组件或者兄弟组件之间传递数据时非常有用。 #### 基本用法 1. **创建全局事件总线** 在 `main.js` 或入口文件中,通过将一个新的 Vue 实例挂载到 `Vue.prototype` 上来创建一个全局事件总线。这样可以在任何组件中通过 `this.$bus` 访问它。 ```javascript // main.js new Vue({ el: '#app', router, store, beforeCreate() { Vue.prototype.$bus = this; // 安装全局事件总线 }, render: h => h(App) }); ``` 2. **监听事件** 在需要接收事件的组件中,使用 `this.$bus.$on('event-name', callback)` 来监听特定事件。通常建议在 `mounted` 生命周期钩子中添加监听器,并在 `beforeDestroy` 或 `unmounted` 钩子中移除监听器以避免内存泄漏。 ```javascript // Home.vue mounted() { this.$bus.$on("homeImgLoad", () => { this.$refs.scroll.scroll.refresh(); }); } ``` 3. **触发事件** 在需要发送事件的组件中,使用 `this.$bus.$emit('event-name', payload)` 来触发事件并传递参数。 ```javascript // GoodsListItem.vue methods: { imgLoad() { if (this.$route.path.indexOf("/home") !== -1) { this.$bus.$emit("homeImgLoad"); } else if (this.$route.path.indexOf("/detail") !== -1) { this.$bus.$emit("detailImgLoad"); } } } ``` 4. **清除事件监听器** 为了防止内存泄漏,在组件销毁之前应移除事件监听器。可以使用 `this.$bus.$off('event-name')` 来清除特定事件的所有监听器。 ```javascript beforeDestroy() { this.$bus.$off("homeImgLoad"); } ``` #### 示例:图片加载后刷新滚动条 假设有一个图片列表组件,当图片加载完成后需要通知父组件刷新滚动条。 ```vue <!-- GoodsListItem.vue --> <template> <img :src="showImage" alt="" @load="imgLoad" /> </template> <script> export default { methods: { imgLoad() { if (this.$route.path.indexOf("/home") !== -1) { this.$bus.$emit("homeImgLoad"); } else if (this.$route.path.indexOf("/detail") !== -1) { this.$bus.$emit("detailImgLoad"); } } } } </script> ``` ```vue <!-- Home.vue --> <template> <Scroll ref="scroll"></Scroll> </template> <script> export default { mounted() { const refresh = debounce(this.$refs.scroll.refresh, 50); this.$bus.$on("homeImgLoad", () => { refresh(); }); }, beforeDestroy() { this.$bus.$off("homeImgLoad"); } } </script> ``` #### 注意事项 - **避免重复监听**:如果多次调用 `$on` 监听同一个事件而不清理,可能会导致事件被多次触发。 - **及时清理监听器**:在组件销毁前务必使用 `$off` 清理不再需要的监听器,以防止内存泄漏。 - **命名约定**:建议使用具有语义化的事件名称(如 `updateData`, `formSubmitted`),以便于维护和理解。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值