网络编程
位置:首页>> 网络编程>> JavaScript>> 详解vue中的computed的this指向问题

详解vue中的computed的this指向问题

作者:ZJW0215  发布时间:2024-04-27 15:46:56 

标签: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

  • 此时使用匿名函数的形式就可以解决,this指向了vueComponent

  • 或者使用对象的形式,用set()、get()方法也不会出现问题

来源:https://segmentfault.com/a/1190000017262022

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com