vue中的computed的this指向问题

今天在写vue项目时,用到了computed计算属性,遇到了使用箭头函数出现this指向问题,这里记录下

1.箭头函数中的this

  • 箭头函数内部的this是词法作用域,由上下文确定
  • 函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象

2.vue中的computed

  • 使用箭头函数
list: () => {
   console.log(this)
}

《vue中的computed的this指向问题》

  • 不使用箭头函数
allFigure: function() {
   console.log(this)
},

《vue中的computed的this指向问题》

  • 使用get()
allFigure: {
  get() {
    console.log(this);
  }
}

《vue中的computed的this指向问题》

3.自己的理解

  • 在computed中使用箭头函数的话,会导致this指向的不是整个的vueComponent
  • 此时使用allFigure: function() {}的形式就可以解决,this指向了vueComponent
  • 或者使用对象的形式,用set()、get()方法也不会出现问题

正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯^_^)

    原文作者:ZJW0215
    原文地址: https://segmentfault.com/a/1190000017262022
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞