VueJS: why is “this” undefined?

前端 未结 2 1152
慢半拍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条回答
  •  忘了有多久
    2020-11-22 05:29

    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, …}

提交回复
热议问题