[英]Vue.js method - Access to `this` within lodash _each loop
My app has a list of collaborators
, and a checkbox next to each one. 我的应用有一个
collaborators
列表,每个旁边都有一个复选框。
The user can check off multiple collaborators, then click a button to remove them, which triggers the following Vue.js method: 用户可以检查多个协作者,然后单击按钮将其删除,从而触发以下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...]
As you can see in the above code, when handling the ajax response, I attempt to loop through each of the selectedCollaborators
using a lodash's _each
, and for each one, remove that collaborator from the collaborators
data property using splice. 正如你可以在上面的代码中看到,处理Ajax响应的时候,我试图遍历每个的
selectedCollaborators
使用lodash的_each
,并为每一个,从移除合作者collaborators
利用拼接的数据属性。
The problem is this.collaborators
is not accessible within the _.each function and the following error is produced: 问题是
this.collaborators
在_.each函数中不可访问,并产生以下错误:
TypeError: Cannot read property 'collaborators' of undefined
How can I fix this/is there a better way to handle this? 我该如何解决这个/有更好的方法来解决这个问题吗?
What you can do is save this
in a variable. 你可以做的是将
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...]
Try replace function to arrow function with lexical context: 尝试用词汇上下文替换函数到箭头函数:
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.