我正在使用Vue.js创建一个组件。
当在 vue 的生命周期(created
,mounted
,updated
等等)中访问 this
,它的结果为undefined
:
mounted: () => {
console.log(this); // logs "undefined"
},
tags: [faq]
同样的事情也计算属性中发生:
computed: {
foo: () => {
return this.bar + 1;
};
}
我收到以下错误:
Uncaught TypeError: Cannot read property 'bar' of undefined
在这些情况下为什么 this
为 undefined
?
解决方法
这两个示例都使用箭头函数 () => { }
,它绑定this
到与 Vue 实例不同的上下文。
根据文档:
不要在实例属性或回调(例如
vm.$watch('a', newVal => this.myMethod())
)上使用箭头函数。由于箭头函数绑定到父上下文,this
因此不会像您期望的那样是 Vue 实例并且this.myMethod
将是 undefined
为了获得 this 作为 Vue 实例的正确引用,请使用常规函数:
mounted: function () {
console.log(this);
}
或者,您也可以对函数使用 ECMAScript 5 shorthand:
mounted() {
console.log(this);
}