我正在使用 Vue.js 创建一个组件。
When I reference this
in any of the the lifecycle hooks ( created
, mounted
, updated
, etc.) it evaluates to undefined
:
mounted: () => {
console.log(this); // logs "undefined"
},
我的计算属性中也发生了同样的事情:
computed: {
foo: () => {
return this.bar + 1;
}
}
我收到以下错误:
未捕获的类型错误:无法读取未定义的属性“bar”
为什么在这些情况下 this
评估为 undefined
?
原文由 thanksd 发布,翻译遵循 CC BY-SA 4.0 许可协议
这两个示例都使用 箭头函数
() => { }
,它将this
绑定到与 Vue 实例不同的上下文。根据 文档:
为了正确引用
this
作为 Vue 实例,请使用常规函数:或者,您也可以对函数使用 ECMAScript 5 简写: