vue.js - 错误:无法读取未定义的属性(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
})
}
}
解决方案
EventBus 应该像这样导入
import { EventBus } from '@/main.js'
如果你想通过
$emit
你应该使用对象传递多个值。
代替
EventBus.$emit('emited', this.height, this.width);
和
EventBus.$emit('emited', {height: this.height, width: this.width});
然后对于听众:
EventBus.$on('emited', function ({height, width}) ...
推荐阅读
- angular - 如何在 TypeScript 中正确使用 GeolocationPosition?
- html - 使用 BeautifulSoup 抓取非内联样式的 html 元素的 css 属性
- python - 类型错误:只能将 str(不是“float”)连接到 str
- r - 如何在 sparklyr 包中运行 FPGrowth
- python - 我无法显示 Django 表单
- jquery - jQuery validate submitHandler 不会触发
- spring - 在 Spring Boot 显示中请求无效或未知 URL 时如何重定向到错误页面
- javascript - 如何使轮播的上一个和下一个按钮工作?
- c++ - 难忘的工厂:不适用于默认的可构造对象
- sql-server - SQL Server 图表以获取连接到节点的多个节点类型