首页 > 解决方案 > 如何在 vue 中添加 eventlistener 并访问 this.$refs 中的组件

问题描述

我的根组件的结构是这样的

<Header />
<router-view>
 <somecomponent>
   <component A ref="componentA" />
   <component B ref="componentB" />
 </somecomponent>
</router-view>
<Footer />

我正在使用事件总线在标头中的组件和路由器视图中的组件之间进行通信,按照将组件从 vue 中的子级添加到父级

当在router-view的somecomponent中接收到一个事件时,我想通过this.$refs.componentA对componentA做一些事情。

我将 eventlistener 添加到 somecomponent 中,如下所示:

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);
        }); 

到某个组件的安装和更新,但结果相同。

我应该在哪里放置事件监听器以避免上述错误的任何想法?

标签: javascriptvue.jsvuejs2vue-component

解决方案


推荐阅读