作用:任意组件间通信
1、在main.js中安装全局事件总线
new Vue({
router,
store,
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this // 安装全局事件总线
}
}).$mount('#app')
2、在需要接收数据的组件中定义自定义事件
mounted() {
this.$bus.$on('getName', data => { // 直接写回调函数必须使用箭头函数,不然this指向有问题
console.log('School 收到了:', data)
this.studentName = data
})
},
beforeDestroy() {
this.$bus.$off('getName')
}
2.1 这里的对调函数也可以写在外面,methods中,例如
methods: {
sendMessage(data) {
console.log('School组件收到了数据:', data)
this.studentName = data
}
},
mounted() {
this.$bus.$on('getName', this.sendMessage)
},
beforeDestroy() {
this.$bus.$off('getName') // 如果解绑多个事件可以使用 (['getName','事件名2',...])
}
注意事项,最好在beforeDestroy钩子函数中使用$off解绑当前组件实例对象所用到的自定义事件
3、提供数据的Student组件
<template>
<div>
<button @click="sendName">get名字</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: '张飞'
}
},
methods: {
sendName() {
this.$bus.$emit('getName', this.name)
}
}
}
</script>
Thanks for your blog, nice to read. Do not stop.