Vue js 与事件总线的非子父通信不起作用 [英] Vue js non child parent communication with event bus does not work
问题描述
在vue js文档中,有一种非父子组件之间通信的方式.vue 文档.但是当我尝试这种方法时,它不起作用.下面是我的代码.有什么帮助吗?
html 页面:
<身体><div id="app10"><component3 :id="id"></component3><component4 :id="id"></component4>
</正文</html>
js 脚本:
var bus = new Vue();Vue.component('component3', {模板:`<div @click='change'>{{ID}}
`,道具:['id'],方法: {改变() {console.log('??? component3 发出');bus.$emit('idSelected', 3);}},安装(){}});Vue.component('component4', {模板:`<div>{{ID}}
`,道具:['id'],});var app10 = new Vue({el: '#app10',数据:函数(){返回 {ID: '?'}},安装(){bus.$on('idSelected', function(value) {console.log('??? app10 点击事件值:', value);this.id = 值;console.log('??? this.id', this.id);});},方法: {}});
我想要做的是:当我单击 component3 时,它的文本内容应该从问号?"更改为到数字 3".但它不起作用.即使父数据的 'id' 变成了 '3',子 props 的 'id' 根本没有改变.为什么?
控制台输出:
<代码>???组件 3 发出???app10 点击事件值:3???这个.id 3
这是一个范围界定问题.调整您的 mounted
钩子如下:
mounted() {const self = this;//保存指向当前'this'的指针bus.$on('idSelected', function(value) {console.log('??? app10 点击事件值:', value);self.id = 值;//这里使用'self'console.log('??? this.id', this.id);});}
否则你会失去对当前this"的引用,因为它在你的事件监听器中等于bus".尝试在您的侦听器中 console.log(this === bus)
(== true).
In vue js document, there is a way to communicate between non parent child components.vue document. But when I tried this method, it did not work. Below is my code. Is there any help?
The html page:
<html>
<body>
<div id="app10">
<component3 :id="id"></component3>
<component4 :id="id"></component4>
</div>
</body
</html>
The js script:
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: {
}
});
What I want to do is: when I click the component3, its text content should change from 'question mark ?' to 'number 3'. But it does not work. Even if the 'id' from the parent data changed to '3', the 'id' of child props did not change at all. Why?
The console output:
??? component3 emit
??? app10 click event value: 3
??? this.id 3
This is a scoping issue. Adjust your mounted
hook as follows:
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);
});
}
Otherwise you loose a reference to current 'this', because it equals to 'bus' in your event listener. Try to console.log(this === bus)
inside your listener ( == true).
这篇关于Vue js 与事件总线的非子父通信不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!