[Vue] Basic 10-minute Todos app
Apr. 15, 2021The Todos app will have three functionalities: delete todo item, add new todo, and clear all todo. All the code will be written in the App.vue file.
Display Todos
First we are going to display Todo items using dummy data.
<template>
<div class="text-2xl">🚀 Todo App 🚀</div>
<div v-for="todo in todos" v-bind:key="todo.id">{{ todo.text }}</div>
</template>
<script>
export default {
name: "App",
data() {
return {
todos: [
{
id: Math.random(),
text: "hello",
},
{
id: Math.random(),
text: "world",
},
],
};
},
};
</script>
Let’s go through the code. First, we are going to create the data() object that contains the todos list. We populate the todos list with two Todo items as shown. Then we display the items by using v-for to iterate through the list and display the items.
Remove Todo item
Next, we add the removeTodo() functionality.
<template>
... {{ todo.text }}
<button @click="removeTodo(todo.id)">❌</button>
</template>
<script>
...
methods: {
removeTodo(todoId) {
this.todos = this.todos.filter(todo => todo.id !=== todoId);
}
}
</script>
We add the remove button to the template and listen to the event on @click. When the button is clicked on, it will trigger the function removeTodo(). This function will take in the id of the todo item, and filter the todos list with items that are not equal to the id of the removed item.
Add new Todo
Add an input textfield and another button to the template.
<template>
...
<div>
<input type="text" v-model="todo" placeholder="add todo..." />
<button @click="addTodo()">Add</button>
</div>
</template>
<script>
...
methods: {
removeTodo(todoId) {
...
},
addTodo() {
if (this.todo.length === 0) {
return;
}
this.todos.push({
id: Math.random(),
text: this.todo
})
}
}
</script>
Similar to removeTodo(), we add a new method addTodo() that is triggered when the button add is clicked on. Noted that we need to bind the value of the input textfield to todo using v-model. v-model can be used to create two-way data bindings on form input, textarea, and select elements. We also add a quick check for empty todo item and only add the item when it’s not empty. Item is added by pusing the new element to the todos list.
Clear all Todos
<template>
...
<div>
<button ...>add</button>
<button @click="clearAllTodos()">clear</button>
</div>
</template>
<script>
...
methods: {
...
clearAllTodos() {
this.todos = [];
}
}
</script>
clearAllTodos is the simplest method. All you need to do is change todos to an empty list.