We continue a sharing last year. Recently, we have started many new sharing series. It is easy and enthusiastic to open up new ones. We all like to try new ones. This is the essence of human nature and the source of human progress. But we need to care about the existing rationally and maintain the existing. So stop and maintain some of the previous sharing.
Deleting function
We need the vue side to implement this method to delete a todo record
- Let's see how the deletion function is implemented in jquery.
destroy: function (e) { this.todos.splice(this.getIndexFromEl(e.target), 1); this.render(); }
2. Then we add the event of listening to click in the delete button @ Click = "removetodo"( todo.id)"
<div class="view"> <input class="toggle" v-model="todo.completed" type="checkbox" :checked="todo.completed"> <label>{{ todo.title}}</label> <button class="destroy" @click="removeTodo(todo.id)"></button> </div>
We implement the removeTodo(id) method in the method of vue. Here we use the filter method of array to filter out the deleted objects.
removeTodo(id){ this.todos= this.todos.filter((todo)=> todo.id != id); },
But when we refresh the webpage again, we find that the record is still there, because we did not update the record in localstorage. Do we need to call the deletion method for each deletion? Is this too troublesome? vue provides a watch to let us monitor an object.
watch: { todos:{ deep:true, handler:'saveTodos' } },
- Deep means deep replication
- handler makes us handle
Then we write our handle, saveTodos, and we call the store method.
saveTodos(){ this.store('todos-jquery',this.todos) },
Screening function
Next, we will do our transfer filtering function. First, let's see how to implement filtering in jquery
getActiveTodos: function () { return this.todos.filter(function (todo) { return !todo.completed; }); }, getCompletedTodos: function () { return this.todos.filter(function (todo) { return todo.completed; }); }, getFilteredTodos: function () { if (this.filter === 'active') { return this.getActiveTodos(); } if (this.filter === 'completed') { return this.getCompletedTodos(); } return this.todos; },
- First, we copy these methods to computed
- Let's change some of the method names and remove the previous get.
computed: { activeTodos() { return this.todos.filter(function (todo) { return !todo.completed; }); }, completedTodos() { return this.todos.filter(function (todo) { return todo.completed; }); }, filteredTodos() { if (this.filter === 'active') { return this.activeTodos(); } if (this.filter === 'completed') { return this.completedTodos(); } return this.todos; } },