问题
The structure of my root component is something like this
<Header />
<router-view>
<somecomponent>
<component A ref="componentA" />
<component B ref="componentB" />
</somecomponent>
</router-view>
<Footer />
I am using an event bus to communicate between components in the header and components in the router-view as per adding component to parent from child in vue
When receiving an event in the somecomponent in router-view, I would like to do something to componentA through this.$refs.componentA.
I add the eventlistener to somecomponent like this:
EventBus.$on("someevent", args => {
this.onSomeEvent(args);
});
and define the method like this:
methods: {
onSomeEvent(args) {
this.$refs.componentA.doSomething();
},
This works fine until I change the page and then go back to the page with somecomponent. Then I start getting the error
Error in event handler for "someEvent": "TypeError: this.$refs.componentA is undefined"
TypeError: "this.$refs.componentA is undefined"
onSomeEvent somecomponent.vue
But the action "doSomething()" is still executed. So it is as if the eventhandler is triggered twice and on the first run that this.$refs.componentA is undefined, where as it is defined on the second run.
I have tried adding the eventlistener
EventBus.$on("someevent", args => {
this.onSomeEvent(args);
});
to somecomponent's mounted and updated but with the same result.
Any ideas where I should place the eventlistener to avoid the error above?
来源:https://stackoverflow.com/questions/58595857/how-to-add-eventlistener-in-vue-and-have-access-to-components-in-this-refs