非父子组件通信

对于非父子组件通信,可以使用一个空的Vue实例来作为中央事件线。

index.html

index.js

   let eventHub = new Vue();
    Vue.prototype.$eventHub = eventHub;

    Vue.component('component-a',{
        template: `
a
`, methods: { send (){ // this.__proto__ === Vue.prototype this.$eventHub.$emit('receive','hi') } } }); Vue.component('component-b',{ template: `
b
`, created (){ this.$eventHub.$on('receive',(data) => { this.$refs.output.textContent = data }) } }); let app = new Vue({ el: '#app' });

点击 a 之后可以看到 hi 传给了 b


image.png

你可能感兴趣的:(非父子组件通信)