【问题标题】:Error: Cannot read property of undefined (Vue)错误:无法读取未定义的属性(Vue)
【发布时间】:2019-10-25 17:06:16
【问题描述】:

我想将数据从一个组件提供给另一个组件。因此,第一个组件应该在数据更新时发出 BusEvent。调用了更新的函数,但我的控制台中总是出现错误:更新钩子中的错误:“TypeError:无法读取未定义的属性'$emit'”

其他组件也不接收高度/宽度。我在这里遇到同样的错误:TypeError: Cannot read property '$emit' of undefined.

刚开始学习vue,不明白怎么回事。非常感谢您的帮助!

height 和 width 在组件 1 中被初始化,所以这不是问题。

//Definition of EventBus in main.js file
export const EventBus = new Vue(); 

//First Component
import EventBus from '@/main.js'
export default {
  data: function () {
    return {    
      height: '',
      width: ''
    }
  },

  updated() {
    EventBus.$emit('emited', this.height, this.width);
  }
}


//Second Component
import EventBus from '@/main.js'
export default {
  data: function () {
    return {
      height: '',
      width: ''
    }
  },

  mounted() {
    const self = this
    EventBus.$on('emited', function (height, width) {
      alert('WORKS!')
      self.height = height
      self.width = width
    })
  }
}

【问题讨论】:

  • 你是如何在 main.js 中定义你的 EventBus 的?
  • 我是这样做的:export const EventBus = new Vue();
  • 你应该像import { EventBus } from '@/main.js'那样导入它

标签: vue.js


【解决方案1】:
  1. EventBus 应该像这样导入 import { EventBus } from '@/main.js'

  2. 如果你想通过$emit传递多个值,你应该使用object。

替换

EventBus.$emit('emited', this.height, this.width);

EventBus.$emit('emited', {height: this.height, width: this.width});

然后对于听众:

EventBus.$on('emited', function ({height, width}) ...

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 2021-08-30
    • 2021-03-29
    • 2019-06-06
    • 1970-01-01
    • 2020-10-15
    • 2022-06-28
    相关资源
    最近更新 更多