Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a to-do list app with Vue 3 and JavaScript.
Create the Project
We can create the Vue project with Vue CLI.
To install it, we run:
npm install -g @vue/cli
with NPM or:
yarn global add @vue/cli
with Yarn.
Then we run:
vue create todo-list
and select all the default options to create the project.
We also need the uuid package to let us generate unique IDs for our to-do items.
To do this, we run:
npm i uuid
Create the To-Do List
To create the to-do list, we write:
<template>
<div>
<form @submit.prevent="add">
<input v-model="todo" />
<button type="submit">Add</button>
</form>
<div v-for="(todo, index) of todos" :key="todo.id">
{{ todo.todo }}
<button @click="deleteTodo(index)">delete</button>
</div>
</div>
</template>
<script>
import { v4 as uuidv4 } from "uuid";
export default {
name: "App",
data() {
return {
todo: "",
todos: [],
};
},
methods: {
add() {
const { todo } = this;
this.todos.push({
id: uuidv4(),
todo,
});
this.todo = "";
},
deleteTodo(index) {
this.todos.splice(index, 1);
},
},
};
</script>
We have the form with the @submit directive to let us submit the form.
The prevent modifier lets us submit our form on the client-side instead of the server-side.
Then we add v-for to render the to-do items.
The key prop is set to the id property, which is the unique ID for a to-do item.
We also have a button in each row to delete an item at the given index with the deleteTodo method.
In the component object, we have the todo reactyive property, which is bound to the input with v-model .
todos has an array of to-do items.
The add method calls the push method to append an item to the this.todos array.
We call the uuidv4 function to return a unique ID we use for the to-do item.
Then we make the this.todo reactive property an empty string to clear the input.
In the deleteTodo method, we call splice with the index and 1 to delete the to-do item at the given index.
Conclusion
We can create a to-do list easily with Vue 3 and JavaScript.