Vue 全局事件总线
全局事件总线
事件总线其实就是vm或vc. 可以在任意组件之间通信。
具体实现是在beforeCreate里面将vm挂到Vue.prototype上去,因为VueComponent.prototype.proto === Vue.prototype
在组件的beforeDestory中要把事件总线订阅的事件解绑
案例
注册事件总线
import Vue from 'vue'
import App from './App.vue'
// 关闭Vue的生产提示
Vue.config.productionTip = false
new Vue({
render: h => h(App),
beforeCreate() {
// 注册事件总线
Vue.prototype.$eventbus = this
}
}).$mount('#app')
App.vue
Child.vue
{{ item.title }}