美文网首页
非父子组件通信

非父子组件通信

作者: 苦瓜_6 | 来源:发表于2018-09-26 21:03 被阅读0次

对于非父子组件通信,可以使用一个空的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


image.png

相关文章

网友评论

      本文标题:非父子组件通信

      本文链接:https://www.haomeiwen.com/subject/lsddwftx.html