我的根组件的结构是这样的
<Header />
<router-view>
<somecomponent>
<component A ref="componentA" />
<component B ref="componentB" />
</somecomponent>
</router-view>
<Footer />
我正在使用事件总线按照adding component to parent from child in vue
在标头中的组件和路由器视图中的组件之间进行通信当在路由器视图的somecomponent中接收到事件时,我想通过this。$ refs.componentA对componentA做些事情。
我将eventlistener添加到这样的某个组件中:
EventBus.$on("someevent", args => {
this.onSomeEvent(args);
});
并定义如下方法:
methods: {
onSomeEvent(args) {
this.$refs.componentA.doSomething();
},
这很好,直到我更改页面,然后返回带有某些组件的页面。 然后我开始得到错误
Error in event handler for "someEvent": "TypeError: this.$refs.componentA is undefined"
TypeError: "this.$refs.componentA is undefined"
onSomeEvent somecomponent.vue
但是动作“ doSomething()”仍然被执行。因此,好像事件处理程序被触发两次,并且在第一次运行时,this。$ refs.componentA是未定义的,而在第二次运行时已定义。
我尝试添加事件监听器
EventBus.$on("someevent", args => {
this.onSomeEvent(args);
});
已安装并更新了某个组件,但结果相同。
有什么主意应该在哪里放置事件监听器以避免上面的错误?