vue组件之非父子组件通信

关键词:通信

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

   var bus = new Vue()

   // 触发组件 A 中的事件
   bus.$emit('id-selected', 1);

   // 在组件 B 创建的钩子中监听事件
   bus.$on('id-selected', function (id) {
    // ...
   })

实例

    
  var Event = new Vue();   // 空组件
        var A = {
          template:`
          
我是A组件->{{a}}
`, methods:{ send(){ Event.$emit('a-msg',this.a); // 触发组件 A 中的事件 } }, data:function(){ return { a:'我是a数据' } } } var B={ template:`
我是B组件->{{a}}
`, methods:{ send(){ Event.$emit('b-msg',this.a); // 触发组件B中的事件 } }, data:function(){ return { a:'我是b数据' } } }
    var C={
      template:`
        

我是C组件

接收过来的A的数据为: {{a}}
接收过来的B的数据为: {{b}}
`, data: function(){ return { a:'', b:'' } }, mounted:function(){ //var _this=this; Event.$on('a-msg',function(a){ // 在组件C 创建的钩子中监听事件 this.a=a; }.bind(this)); Event.$on('b-msg',function(a){ // 在组件C 创建的钩子中监听事件 this.b=a; }.bind(this)); } };
window.onload=function(){
    new Vue({
        el:'#box',
        components:{
            'com-a':A,
            'com-b':B,
            'com-c':C
        }
    });
};

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