gpt4 book ai didi

javascript - Vue js非子父级与事件总线的通信不起作用

转载 作者:行者123 更新时间:2023-12-01 03:29:23 25 4
gpt4 key购买 nike

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

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: {
}
});

我想要做的是:当我点击组件3时,它的文本内容应该从“问号?”改变到“3号”。但这不起作用。即使父数据中的“id”更改为“3”,子 props 的“id”也根本没有改变。为什么?

控制台输出:

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

最佳答案

这是一个范围界定问题。按如下方式调整 mounted Hook :

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);
});
}

否则您将丢失对当前“this”的引用,因为它等于事件监听器中的“bus”。尝试在监听器中使用 console.log(this === bus) ( == true)。

关于javascript - Vue js非子父级与事件总线的通信不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44624855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com