我有两个单独的Vue组件,它们需要通过eventbus相互通信。像这样:
form-component.Vue
import events from './events'
export default {
...
methods() {
sumbitForm() {
events.$emit('form-submitted', data)
}
}
...
}other-component.Vue
import events from './events'
export default {
....
mounted() {
events.$on('form-submitted, data => {
this.list.push(data);
}
},
data() {
return {
list: []
}
}
....
}但是当事件被监听时,'this‘不是指'other-component’,而是指实际的eventbus 'events‘。
我该如何解决这个问题呢?
发布于 2018-04-11 20:25:56
在我看来,你好像误解了这个问题。箭头函数绑定它的上下文,并且该箭头函数的上下文被正确地绑定到另一个组件,因为它在一个方法中,并且方法被自动绑定到它们的组件。下面的示例按照预期工作。
const events = new Vue();
Vue.component('formComponent', {
template: '<button @click="submitForm">Submit</button>',
methods: {
submitForm() {
events.$emit('form-submitted', {
foo: 1
});
}
}
});
Vue.component('otherComponent', {
template: '<div><div v-for="item in list">{{item}}</div></div>',
data() {
return {
list: []
}
},
mounted() {
events.$on('form-submitted', data => {
this.list.push(data);
});
}
});
new Vue({
el: '#app'
});<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<form-component></form-component>
<other-component></other-component>
</div>
发布于 2018-04-11 20:00:36
一种解决方案是将this复制到外部变量中,并使用该变量访问组件的数据属性。例如,这应该是可行的:
import events from './events'
export default {
....
mounted() {
var that = this;
events.$on('form-submitted, function(data) {
that.list.push(data);
)
},
data() {
return {
list: []
}
}
....
}https://stackoverflow.com/questions/49774392
复制相似问题