[英]Vue.js event bus
I'm working on a vue single page project,and I use an empty Vue instance as a central event bus.But there is some problem when firing a event. 我正在开发一个vue单页项目,我使用一个空的Vue实例作为中央事件总线。但是在触发事件时存在一些问题。
eventbus.js eventbus.js
import vue from 'Vue'
export default new vue({})
a.vue a.vue
import bus from '~js/eventBus'
methods: {
go(name) {
bus.$emit('setPartner', name);
this.$router.go(-1);
}
}
b.vue b.vue
import bus from '~js/eventBus'
data() {
return {
contract: {
contractSubject: ''
}
}
},
mounted(){
bus.$once('setPartner', data => {
this.contract.contractSubject = data;
});
}
in b.vue file,I can recieve data,but I can't assign the value of data to 'this.contract.contractSubject' 在b.vue文件中,我可以接收数据,但我无法将数据值分配给'this.contract.contractSubject'
I would comment, but point restrictions. 我会评论,但指出限制。 It seems like you're only posting snippets of the code, so it's hard to get a full picture. 您似乎只发布了代码片段,因此很难全面了解。 I assume that you've already set this.contract to be an Object? 我假设你已经将this.contract设置为Object? I don't know what your data function looks like, and an error message would be helpful, but it sounds like you're trying to assign a field on an object that doesn't exist yet. 我不知道您的数据函数是什么样的,并且错误消息会有所帮助,但听起来您正试图在尚不存在的对象上分配字段。
Edit 编辑
Thanks for the information. 谢谢提供信息。 I'm not sure if your edit to b.vue was a mistake when you copied things over to stackoverflow, but based on the code you've provided, my guess is that you wrote data()
in the wrong place. 当你把东西复制到stackoverflow时,我不确定你对b.vue的编辑是否是一个错误,但根据你提供的代码,我的猜测是你在错误的地方写了data()
。 You have it inside mounted()
, not as a key value of the component object, and thus this.contract
won't access it. 你有mounted()
内部,而不是组件对象的键值,因此this.contract
将不会访问它。
I managed to get it working under the setup below 我设法在下面的设置下工作
a.vue a.vue
import bus from './bus.js';
export default {
name: 'sitea',
methods: {
go(name) {
bus.$emit('setPartner', name);
}
}
}
b.vue b.vue
import bus from './bus.js'
export default {
name: 'siteb',
data() {
return {
contract: {
contractSubject: ''
}
}
},
mounted() {
bus.$once('setPartner', data => {
console.log(data);
this.contract.contractSubject = data;
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.