跳到主内容

VueJs的this是undefined

· 2分钟阅读

我正在使用Vue.js创建一个组件。

当在 vue 的生命周期createdmountedupdated等等)中访问 this,它的结果为undefined

mounted: () => {
console.log(this); // logs "undefined"
},

tags: [faq]

同样的事情也计算属性中发生:

computed: {
foo: () => {
return this.bar + 1;
};
}

我收到以下错误:

Uncaught TypeError: Cannot read property 'bar' of undefined

在这些情况下为什么 thisundefined

解决方法

这两个示例都使用箭头函数 () => { },它绑定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);
}