首页 > 解决方案 > 错误:无法读取未定义的属性(Vue)

问题描述

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

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

我刚开始学习vue,我不明白出了什么问题。非常感谢你的帮助!

高度和宽度在组件一中被初始化,所以这不是问题。

//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
    })
  }
}

标签: vue.js

解决方案


  1. EventBus 应该像这样导入import { EventBus } from '@/main.js'

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

代替

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

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

然后对于听众:

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


推荐阅读