狐的傳說
2019-06-24 09:42:05
VueJS:為什么“這個”沒有定義?我正在創建一個組件vue.js.當我提到this在任何一個生命周期鉤 (created, mounted, updated等等)它評估為undefined:mounted: () => {
console.log(this); // logs "undefined"},同樣的事情也發生在我的計算屬性中:computed: {
foo: () => {
return this.bar + 1;
} }我得到以下錯誤:未定義類型錯誤:無法讀取未定義的屬性“bar”為什么this評估到undefined在這種情況下?
2 回答

翻翻過去那場雪
TA貢獻2065條經驗 獲得超14個贊
() => { }
this
不要對實例屬性或回調使用箭頭函數(例如, vm.$watch('a', newVal => this.myMethod())
)。當箭頭函數綁定到父上下文時, this
不會如您所期望的那樣成為Vue實例, this.myMethod
將是未知的。
this
mounted: function () { console.log(this);}
mounted() { console.log(this);}

波斯汪
TA貢獻1811條經驗 獲得超4個贊
this
this
this
var instance = new Vue({ el:'#instance', data:{ valueOfThis:null }, created: ()=>{ console.log(this) }});
Window {postMessage: ?, blur: ?, focus: ?, close: ?, frames: Window, …}
var instance = new Vue({ el:'#instance', data:{ valueOfThis:null }, created: function(){ console.log(this) }});
hn {_uid: 0, _isVue: true, $options: {…}, _renderProxy: hn, _self: hn, …}
添加回答
舉報
0/150
提交
取消