我有一个这样的组件结构:
/parent
/childA
/childB
我想从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次。
事件清除成功后,为什么会出现这些错误?
如果有帮助的话,我从这篇文章中得到了我的代码。
试试这个:
For emit在你的组件中:
this.$emit('message', 'hello')
在父组件中,你不需要在'mounted()'中创建侦听器。只需在模板部分中,像这样调用该事件的方法:
<component @message="showMessage"/>
然后创建如下方法:
methods: {
showMessage (message) {
console.log(message)
}
}