В моем приложении есть список 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.info('Remove collaborator: ' + value);
// Following line produces: TypeError: Cannot read property 'collaborators' of undefined
this.collaborators.splice(this.collaborators.indexOf(value), 1)
});
});
}
},
// [...etc...]
Как вы можете видеть в приведенном выше коде, при обработке ответа ajax я пытаюсь перебрать каждый из selectedCollaborators
, используя _each
lodash, и для каждого удалить этого соавтора из свойства данных collaborators
, используя splice.
Проблема в том, что 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.info('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.info('Remove collaborator: ' + value);
// Following line produces: TypeError: Cannot read property 'collaborators' of undefined
this.collaborators.splice(this.collaborators.indexOf(value), 1)
});
});
}
},