全局事件总线(GlobalEventBus)
-
一种组件间通信方式,可实现任意组件间通信
-
安装全局事件总线
// main.js中 new Vue({ el: "#app", render: (h) => h(App), beforeCreate() { // 安装全局事件总线 Vue.prototype.$bus=this } })
-
使用事件总线
-
接收数据:需要就收数据的组件中给$bus绑定自定义事件,事件的回调在该组件自身
//School组件 mounted() { this.$bus.$on('hello',(data)=>{ console.log('我是School组件,收到了数据',data) }) }, beforeDestroy() { this.$bus.$off('hello') }
-
提供数据:
this.$bus.$emit('事件名',数据)
// Student组件 methods:{ sentStudentName(){ this.$bus.$emit('hello',this.names) } }
-
-
最好在使用off方法解绑当前组件所用到的事件
Todo-list案例全局事件总线
- 在main.js中配置全局事件总线
- 删除原来使用的props方法传递的事件
- 在需要接收数据的App组件中配置相应钩子及函数
- 在需要提供数据的Item组件中绑定事件名
main.js
new Vue({
el: "#app",
render: (h) => h(App),
beforeCreate() {
Vue.prototype.$bus=this
}
});
App组件
<List :todoArr="todoArr"></List>
mounted() {
this.$bus.$on('checkTodo',this.checkTodo)
this.$bus.$on('deleteTodo',this.deleteTodo)
},
beforeDestroy() {
this.$bus.$off(['checkTodo','deleteTodo'])
}
List组件
<Item v-for="item in todoArr"
:key="item.id"
:todo="item">
</Item>
props: ['todoArr']
Item组件
props: ['todo'],
methods: {
handleCheck(id) {
//通知App组件将对应的todo对象的done值进行修改
// this.checkTodo(id)
this.$bus.$emit('checkTodo',id)
},
// 删除任务项
deleteItem(id){
if (confirm('确定要删除此任务吗?')){
// this.deleteTodo(id)
this.$bus.$emit('deleteTodo',id)
}
}