【发布时间】: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