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 grocery-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 grocery list items.
To do this, we run:
npm i uuid
Create the Grocery List App
To create the grocery list app, we write:
<template>
<div>
<form @submit.prevent="add">
<fieldset>
<label>item</label>
<input v-model="item" />
</fieldset>
<button type="submit">add item</button>
</form>
<div v-for="(item, index) of items" :key="item.id">
{{ item.item }}
<button @click="remove(index)">remove</button>
</div>
</div>
</template>
<script>
import { v4 as uuidv4 } from "uuid";
export default {
name: "App",
data() {
return {
item: "",
items: [],
};
},
methods: {
add() {
const { item } = this;
this.items.push({
id: uuidv4(),
item,
});
},
remove(index) {
this.items.splice(index, 1);
},
},
};
</script>
We have the form element with the @submit
directive to let us listen to submit events, which is triggered when we click add item.
v-model
is bound to item
so that we can get the entered value from the add
method.
With the v-for
directive, we render the added items.
The key
is required to be a unique ID, so that Vue 3 can keep track of the items in the rendered list.
We have the remove button to remove the item.
In the component object, we have the data
method to define the item we want to add.
items
have the items we added.
In add
, we call this.items.push
to add an item to the grocery list.
We generate a unique ID for each item with the uuidv4
function.
In the remove
method, we call this.items.splice
to remove an item by its index.
Now we can add and remove items from the grocery with the add item button and remove button respectively.
Conclusion
We can write a grocery list app easily with Vue 3 and JavaScript.