VueJS: why is “this” undefined?

前端 未结 2 1149
慢半拍i
慢半拍i 2020-11-22 05:02

I\'m creating a component with Vue.js.

When I reference this in any of the the lifecycle hooks (created, mounted, updat

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:43

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

提交回复
热议问题