今天在寫vue項目時,用到了computed計算屬性,遇到了使用箭頭函數出現this指向問題,這裏記錄下
1.箭頭函數中的this
- 箭頭函數內部的this是詞法作用域,由上下文確定
- 函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象
2.vue中的computed
- 使用箭頭函數
list: () => {
console.log(this)
}
- 不使用箭頭函數
allFigure: function() {
console.log(this)
},
- 使用get()
allFigure: {
get() {
console.log(this);
}
}
3.自己的理解
- 在computed中使用箭頭函數的話,會導致this指向的不是整個的vueComponent
- 此時使用匿名函數的形式就可以解決,this指向了vueComponent
- 或者使用對象的形式,用set()、get()方法也不會出現問題
正在努力學習中,若對你的學習有幫助,留下你的印記唄(點個贊咯^_^)