Vue中的 this

578 阅读1分钟

1. Vue中生命周期钩子和自定义方法中的this指向当前的 Vue 实例

Vue2官方文档这样写到:

  • 生命周期钩子的 this 上下文指向调用它的 Vue 实例

所有的生命周期钩子自动绑定 this 上下文到实例中,因此你可以访问数据,对 property 和方法进行运算。这意味着你不能使用箭头函数来定义一个生命周期方法 (例如 created: () => this.fetchTodos())。这是因为箭头函数绑定了父上下文,因此 this 与你期待的 Vue 实例不同,this.fetchTodos 的行为未定义。

2. Vue 中回调函数中的 this

methods:{
  logThis(){
      console.log(this,'methods中的this');
    },
   onClick(){
      console.log(this,'vue中的this');
      setTimeout(this.logThis)
      setTimeout(function () {
        console.log(this,'回调函数中bind前的this');
      })
      setTimeout(function () {
        console.log(this,'回调函数中bind后的this');
      }.bind(this))
   }
  }

从上面的结果可知: Vue 中setTimeout回调函数中的this指向

  1. 若回调函数为匿名函数,非严格模式下指向 window,严格模式下为 undefined。
  2. 若回调函数为自定义方法,则 this 指向 Vue 实例。
  3. 若回调函数为 箭头函数,则 this 指向 Vue 实例。

3. Vue 中 addEventListener 中的 this

通常,事件监听函数中的 this 都指向绑定事件的那个元素, 但是在 Vue 中,监听函数中的 this 也指向 Vue 实例

总结:除了回调函数中的 this ,其它地方的 this 均指向 Vue 实例