[英]Vue.js method - Access to `this` within lodash _each loop
我的應用有一個collaborators
列表,每個旁邊都有一個復選框。
用戶可以檢查多個協作者,然后單擊按鈕將其刪除,從而觸發以下Vue.js方法:
methods: {
remove: function () {
if (confirm('Are you sure you want to delete these collaborators?')) {
axios.get('/collaborators/api/destroy', {
params: {
ids: this.selectedCollaborators
}
})
.then(response => {
// Loop through the `selectedCollaborators` that were deleted and
// remove them from `collaborators`
_.each(this.selectedCollaborators, function (value, key) {
console.log('Remove collaborator: ' + value);
// Following line produces: TypeError: Cannot read property 'collaborators' of undefined
this.collaborators.splice(this.collaborators.indexOf(value), 1)
});
});
}
},
// [...etc...]
正如你可以在上面的代碼中看到,處理Ajax響應的時候,我試圖遍歷每個的selectedCollaborators
使用lodash的_each
,並為每一個,從移除合作者collaborators
利用拼接的數據屬性。
問題是this.collaborators
在_.each函數中不可訪問,並產生以下錯誤:
TypeError: Cannot read property 'collaborators' of undefined
我該如何解決這個/有更好的方法來解決這個問題嗎?
你可以做的是將this
保存在一個變量中。
methods: {
remove: function () {
if (confirm('Are you sure you want to delete these collaborators?')) {
axios.get('/collaborators/api/destroy', {
params: {
ids: this.selectedCollaborators
}
})
.then(response => {
const t = this;
// Loop through the `selectedCollaborators` that were deleted and
// remove them from `collaborators`
_.each(this.selectedCollaborators, function (value, key) {
console.log('Remove collaborator: ' + value);
t.collaborators.splice(t.collaborators.indexOf(value), 1)
});
});
}
},
// [...etc...]
嘗試用詞匯上下文替換函數到箭頭函數:
methods: {
remove: () => {
if (confirm('Are you sure you want to delete these collaborators?')) {
axios.get('/collaborators/api/destroy', {
params: {
ids: this.selectedCollaborators
}
})
.then(response => {
// Loop through the `selectedCollaborators` that were deleted and
// remove them from `collaborators`
_.each(this.selectedCollaborators, (value, key) => {
console.log('Remove collaborator: ' + value);
// Following line produces: TypeError: Cannot read property 'collaborators' of undefined
this.collaborators.splice(this.collaborators.indexOf(value), 1)
});
});
}
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.