How to add eventlistener in vue and have access to components in this.$refs

筅森魡賤 提交于 2019-12-11 10:50:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!