VueJS: 为什么“这个”没有定义?

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

当我在任何 生命周期挂钩(createdmountedupdated等)中引用 this时,它的计算结果是 undefined:

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

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

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

我得到以下错误:

未捕获的 TypeError: 无法读取未定义的属性“ bar”

为什么在这些情况下 this评估为 undefined

57455 次浏览

Both of those examples use an arrow function () => { }, which binds this to a context different from the Vue instance.

As per the documentation:

Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.

In order to get the correct reference to this as the Vue instance, use a regular function:

mounted: function () {
console.log(this);
}

Alternatively, you can also use the ECMAScript 5 shorthand for a function:

mounted() {
console.log(this);
}

You are using arrow functions.

The Vue Documentation clearly states not to use arrow functions on a property or callback.

Unlike a regular function, an arrow function does not bind this. Instead, this is bound lexically (i.e. this keeps its meaning from its original context).

var instance = new  Vue({
el:'#instance',
data:{
valueOfThis:null
},
created: ()=>{
console.log(this)
}
});

This logs the following object in the console:

Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}

Whereas... If we use a regular function (which we should on a Vue instance)

var instance = new  Vue({
el:'#instance',
data:{
valueOfThis:null
},
created: function(){
console.log(this)
}
});

Logs the following object in the console:

hn {_uid: 0, _isVue: true, $options: {…}, _renderProxy: hn, _self: hn, …}

If you want to keep using the arrow function, you could pass the component instance (this) as parameter like :

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

you cannot use the arrow funtion if you want to use the this. Because the arrow funtion doesn't bind this.