2017-06-19 44 views
0

在vue js文档中,有一种方法可以在非父子组件之间进行通信。 vue document。但是当我尝试这种方法时,它不起作用。以下是我的代码。有什么帮助吗?Vue js与事件总线的父子通信不起作用

HTML页面:

<html> 
    <body> 
     <div id="app10"> 
      <component3 :id="id"></component3> 
      <component4 :id="id"></component4> 
     </div> 
    </body 

</html> 

JS脚本:

var bus = new Vue(); 
Vue.component('component3', { 
    template: ` 
    <div @click='change'> 
     {{id}} 
    </div> 
    `, 
    props: ['id'], 
    methods: { 
    change() { 
     console.log('??? component3 emit'); 
     bus.$emit('idSelected', 3); 
    } 
    }, 
    mounted() { 
    } 
}); 

Vue.component('component4', { 
    template: ` 
    <div> 
     {{id}} 
    </div> 
    `, 
    props: ['id'], 
}); 

var app10 = new Vue({ 
    el: '#app10', 
    data: function() { 
    return { 
     id: '?' 
    } 
    }, 
    mounted() { 
    bus.$on('idSelected', function(value) { 
     console.log('??? app10 click event value: ', value); 
     this.id = value; 
     console.log('??? this.id', this.id); 
    }); 
    }, 
    methods: { 
    } 
}); 

我想要做的是: '问号' 当我点击component3,其文本内容应从改变到'3号'。但它不起作用。即使父数据中的'id'变为'3',儿童道具的'id'根本没有变化。为什么?

控制台输出:

??? component3 emit 
??? app10 click event value: 3 
??? this.id 3 

回答

1

这是一个范围的问题。调整你的mounted钩如下:

mounted() { 
    const self = this; // save pointer to current 'this' 
    bus.$on('idSelected', function(value) { 
     console.log('??? app10 click event value: ', value); 
     self.id = value; // use 'self' here 
     console.log('??? this.id', this.id); 
    }); 
    } 

否则你失去了一个参考电流“本”,是因为它在你的事件监听等于“总线”。尝试在您的监听器中使用console.log(this === bus)(== true)。

+0

傻了,再次犯这个错误。谢谢! – soarinblue

+0

不客气。 – wostex

1

this值在你的代码更改匿名函数里面。使用箭头函数来保留vue实例的上下文。

var bus = new Vue(); 
 
Vue.component('component3', { 
 
    template: ` 
 
    <div @click='change'> 
 
     {{id}} 
 
    </div> 
 
    `, 
 
    props: ['id'], 
 
    methods: { 
 
    change() { 
 
     console.log('??? component3 emit'); 
 
     bus.$emit('idSelected', 3); 
 
    } 
 
    }, 
 
    mounted() { 
 
    } 
 
}); 
 

 
Vue.component('component4', { 
 
    template: ` 
 
    <div> 
 
     {{id}} 
 
    </div> 
 
    `, 
 
    props: ['id'], 
 
}); 
 

 
var app10 = new Vue({ 
 
    el: '#app10', 
 
    data: function() { 
 
    return { 
 
     id: '?' 
 
    } 
 
    }, 
 
    mounted() { 
 
    bus.$on('idSelected', (value) => { 
 
     console.log('??? app10 click event value: ', value); 
 
     this.id = value; 
 
     console.log('??? this.id', this.id); 
 
    }); 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> 
 
<html> 
 
    <body> 
 
     <div id="app10"> 
 
      <component3 :id="id"></component3> 
 
      <component4 :id="id"></component4> 
 
     </div> 
 
    </body> 
 

 
</html>