Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
64 views
in Technique[技术] by (71.8m points)

javascript - VueJS: why is "this" undefined?

I'm creating a component with 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"
},

The same thing is also happening inside my computed properties:

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

I get the following error:

Uncaught TypeError: Cannot read property 'bar' of undefined

Why is this evaluating to undefined in these cases?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...