javascript - 如何在 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);
});
到某个组件的安装和更新,但结果相同。
我应该在哪里放置事件监听器以避免上述错误的任何想法?
解决方案
推荐阅读
- java - Spring Web 控制器如何确定重定向的 HTTP 状态代码
- ruby-on-rails - 为什么 Rails 没有响应错误 406?
- android - Android Kotlin 中的 RecyclerView 效果选定项
- python - 输入一个数字 N,然后程序继续输出所有小于 N 的 2 的幂。我该如何继续?
- reactjs - ReactJS 令牌基础帖子?
- micronaut - 如何从 Mironaut 控制器发送 Base64 编码的 PDF?
- c# - 如何在 C# 代码中使用 Redis 缓存中的 HSET 命令?
- swift - 如何在 WKWebview 中制作按钮刷新页面
- sql - SQL - 将日期移至 48 小时窗口内
- php - 如何记录控制器中出现的问题