美文网首页
1-5 vue组件-非父子组件通信

1-5 vue组件-非父子组件通信

作者: 绣依锐 | 来源:发表于2018-08-28 10:33 被阅读0次

    通过单独的事件中心管理组件间的通信
    将在各处使用该事件中心,组件通过它来通信

    1、先设置Bus

    var eventHub = new Vue()

    然后在组件中,可以使用 emit,on, $off 分别来分发、监听、取消监听事件

    2、发送事件的组件

    Vue.component('component-a',{
        template:'<div>组件A:<button @click="sendDataFromA">向组件B发送组件A的数据</button></div>',
        data() { return { data1:'组件A的数据' } },
         methods: {
            sendDataFromA() {
                eventHub.$emit('sendDataFromA',this.data1)
            }
         }
    })
    

    3、组件内监听事件

    Vue.component(' component-b',{
        template:'<div>组件B:<p>从组件A接收的字符串参数 {{msg}}</p></div>',    
        data(){
            return {msg:'默认值'}
        },
        mounted() {
            var self = this
            eventHub.$on('sendDataFromA',function(data){ self.msg = data })
        }
    })
    

    相关文章

      网友评论

          本文标题:1-5 vue组件-非父子组件通信

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