对于非父子组件通信,可以使用一个空的Vue实例来作为中央事件线。
index.html
<div id="app">
<component-a></component-a>
<component-b></component-b>
</div>
index.js
let eventHub = new Vue();
Vue.prototype.$eventHub = eventHub;
Vue.component('component-a',{
template: `<div> a <button @click = "send"> click </button></div>`,
methods: {
send (){
// this.__proto__ === Vue.prototype
this.$eventHub.$emit('receive','hi')
}
}
});
Vue.component('component-b',{
template: `<div> b <div ref = "output"></div> </div>`,
created (){
this.$eventHub.$on('receive',(data) => {
this.$refs.output.textContent = data
})
}
});
let app = new Vue({
el: '#app'
});
点击 a 之后可以看到 hi 传给了 b