首页 > 解决方案 > VueJS 向组件发出工作但出现错误无法读取应用属性

问题描述

我有一个这样的组件结构:

/parent
  /childA
  /childB

我想从 to 发送消息childAchildB所以在childAVueJS 组件中,我发出这样的事件:

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 帖子中获得了我的代码。

标签: vue.jsevents

解决方案


尝试这个:

对于在您的组件中发出:

this.$emit('message', 'hello')

在您的父组件中,您不需要在“mounted()”处创建侦听器。就在你的模板部分,像这样调用那个事件的方法:

<component @message="showMessage"/>

然后创建一个这样的方法:

methods: {
  showMessage (message) {
    console.log(message)
  }
}

推荐阅读