In a question from Soen, was said to use the Vuex state manager, the methods $delete
and probablythe $set
must not be accessible, which may explain the error message this.$delete is not a function
.
The appropriate would be to use Vue.delete
, but dee according to the documentation, this should be used rarely should be used:
Delete a Property on an Object. If the Object is reactive, ensure the
Deletion triggers view updates. This is primarily used to get Around
the limitation that Vue cannot Detect Property deletions, but you
should rarely need to use it.
In this case, as its state is an array this.todos
, change this object using simple array methods, it will be enough.
Finish a task
How about using the map
?:
toggleTodo(todo) {
this.todos = this.todos.map((item) => {
if (item.id === todo.id) {
item.checked = !item.checked // inverte o estado do 'checked'
}
return item
});
},
See an example to understand the logic:
var persons = [
{ id: 1, checked: false },
{ id: 2, checked: false },
{ id: 3, checked: false }
];
persons = persons.map(item => {
if (item.id === 3) item.checked = true
return item
})
console.log(persons)
Remove a task
How about the splice
?:
removeTodo(todo) {
const index = this.todos.findIndex((item) => item.id === todo.id);
if (index > -1) {
this.todos.splice(index, 1); // não precisa reatribuir ao this.todos
} // pois 'splice' já altera o array original
},
See an example to understand the logic:
var persons = [{
id: 1,
checked: false
},
{
id: 2,
checked: false
},
{
id: 3,
checked: false
}
];
const index = persons.findIndex((item) => item.id === 3);
if (index > -1) {
persons.splice(index, 1);
}
console.log(persons) // removeu o item de id 3
How Vue works with the View concept based on the state (as I mentioned earlier here), change the value of this.todos
will cause a view update.
SS in $set I try to enter a new task and in $delete I try to delete it from array.
– Gabriel Teixeira
Why not
this.todos.splice(index, 1);
?– Cmte Cardeal
Here says it would be
Vue.delete(..)
and rarely should be used. The same goes for the$set
, believe me. So why not work directly with this state using only array methods?– Cmte Cardeal
I’ll post an answer....
– Cmte Cardeal