vue.js - VueJS 向组件发出工作但出现错误无法读取应用属性
问题描述
我有一个这样的组件结构:
/parent
/childA
/childB
我想从 to 发送消息childA
,childB
所以在childA
VueJS 组件中,我发出这样的事件:
this.$root.$emit('message', 'hello')
在childB
组件中,我正在注册一个这样的监听器:
mounted() {
this.$root.$on('message', (arg) => {
console.log('message: '+arg)
})
}
当事件被触发(在用户交互时)时,childA
我在控制台中看到了这个:
[Vue warn]: Error in event handler for "message": "TypeError: Cannot read property 'apply' of undefined"
TypeError: Cannot read property 'apply' of undefined
message:
(3) message: hello
(3)
是出现在圆圈中的数字,3
表示(我相信)同样的事情console.log
已经发生了 3 次。
为什么事件清除成功时会出现这些错误?
如果有帮助,我从这篇 Medium 帖子中获得了我的代码。
解决方案
尝试这个:
对于在您的组件中发出:
this.$emit('message', 'hello')
在您的父组件中,您不需要在“mounted()”处创建侦听器。就在你的模板部分,像这样调用那个事件的方法:
<component @message="showMessage"/>
然后创建一个这样的方法:
methods: {
showMessage (message) {
console.log(message)
}
}
推荐阅读
- javascript - 使用 puppeteer 在具有窗口访问的真实浏览器环境中运行 jest 单元测试
- python - 图形着色问题:为边缘添加颜色
- html - 防止文本包装器在文本溢出到下一行后跨越其父级的整个宽度
- java - Spring-data-aerospike 无法将字段设置为 null
- debugging - 调试 Docker 容器以 0 退出
- kotlin - Kotlin:可见性修饰符更改匿名对象的类型
- java - 使用 Java 将变量传递给 @AndroidFindBy 注解
- wordpress - 内部服务器错误。登录 wordpress 网站时遇到问题
- android - Android WebView:用 PDF 显示网站
- python - Python pandas - 分组、计数、绘制多系列