VueJS发出到组件的作品但出现错误无法读取apply属性 [英] VueJS emit to component works but with error Cannot read apply property
问题描述
我有这样的组件结构:
/parent
/childA
/childB
我想将消息从 childA
发送到 childB
,因此在 childA
VueJS组件中,我发出了如下事件:
I would like to send a message from childA
to childB
, so in childA
VueJS component, I am emitting an event like this:
this.$root.$emit('message', 'hello')
在 childB
组件中,我正在这样注册一个侦听器:
In childB
component, I am registering a listener like this:
mounted() {
this.$root.$on('message', (arg) => {
console.log('message: '+arg)
})
}
当在 childA
中触发事件(通过用户交互)时,我在控制台中看到了这一点:
When the event is fired (upon a user interaction) in childA
I see this in the console:
[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次.
The (3)
is the number 3
appearing in a circle, indicating (I believe) that the same console.log
has occurred 3 times.
事件清除成功后,为什么会发生这些错误?
Why are these errors occurring when the event clearing succeeds?
如果有帮助,我从此媒体获取了我的代码发布.
推荐答案
尝试一下:
要发出组件中的光:
this.$emit('message', 'hello')
并且在您的父组件中,您无需在"mount()"处创建侦听器.只需在您的模板部分中,针对该事件调用一个方法,如下所示:
And in your parent component you don't need to create a listener at 'mounted()'. just in your template section, call a method on that event like this:
<component @message="showMessage"/>
然后创建这样的方法:
methods: {
showMessage (message) {
console.log(message)
}
}
这篇关于VueJS发出到组件的作品但出现错误无法读取apply属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!