1.在main.js文件中,vue示例上挂载$EventBus并实例化
Vue.prototype.$EventBus = new Vue()
2.在组件中触发事件并抛出自定义事件
data() {
return {
// 数据
name: 1,
msg: ''
}
},
methods: {
// 方法
notice() {
this.$EventBus.$emit('hh', this.name++)
}
},
3.在需要接受值的组件内挂载结束后监听自定义事件
data() {
return {
// 数据
name: '我是2,我要通知1',
msg: ''
}
},
mounted() {
// 挂载后
this.$EventBus.$on('hh', msg => {
// A发送来的消息
console.log(msg)
this.msg = msg
})
},
4.最后别忘了销毁
// 在订阅的文件中销毁
destroyed() {
this.$ventBus.$off('hh')
}