-
一种组件间通信的方式,适用于
任意组件间通信
。 -
安装全局事件总线:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })
-
使用事件总线:
-
接收数据:A 组件想接收数据,则在 A 组件中给$bus 绑定自定义事件,事件的
回调留在 A 组件自身。
methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }
-
提供数据:
this.$bus.$emit('xxxx',数据)
-
-
最好在 beforeDestroy 钩子中,用$off 去解绑
当前组件所用到的
事件。
5.案例
利用全局事件总线将Student组件中的name属性传递给School组件
Student.vue
组件
<template>
<div>
<button @click="sendStudentName">把名字传递给school组件</button>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
name: "janny",
};
},
methods: {
sendStudentName() {
this.$bus.$emit("hello", this.name);
},
},
};
</script>
School.vue
组件
<template>
<div>
<h1>School组件</h1>
<h2>{{ name }}</h2>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
name: "小虾皮陈",
age: 18,
};
},
mounted() {
this.$bus.$on("hello", (data) => {
this.name = data;
console.log("我是School组件,收到了数据", data);
});
},
beforeDestroy() {
// 在组件销毁的时候解绑事件
this.$bus.$off("hello");
},
};
</script>
main.js
中的操作:
// 全局事件总线(方案一)
// const Demo = Vue.extend({})
// const d = new Demo()
// Vue.prototype.x = d
new Vue({
router,
store,
render: h => h(App),
// 全局事件总线(方案二)
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线
}
}).$mount('#app')
网友评论