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 flashcard 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 flashcard
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 Flashcard App
To create the flashcard app, we write:
<template>
<form @submit.prevent="add">
<div>
<label>question</label>
<input v-model="item.question" />
</div>
<div>
<label>answer</label>
<input v-model="item.answer" />
</div>
<button type="submit">submit</button>
</form>
<div v-for="(item, index) of items" :key="item.id">
<b>question</b>
<p>{{ item.question }}</p>
<b>answer</b>
<p>{{ item.answer }}</p>
<button @click="deleteItem(index)">delete</button>
</div>
</template>
<script>
import { v4 as uuidv4 } from "uuid";
export default {
name: "App",
data() {
return {
item: {
question: "",
answer: "",
},
items: [],
};
},
methods: {
add() {
this.items.push({
id: uuidv4(),
...this.item,
});
this.item = {};
},
deleteItem(index) {
this.items.splice(index, 1);
},
},
};
</script>
In the template, we have the form to let us enter questions answers into the form.
v-model
binds to the entered question and answer to item.question
and item.answer
reactive properties.
The submit button triggers the submit
event which runs the add
method.
The prevent
modifier stops the default server-side submit behavior.
We use v-for
to render the items in the items
reactive property.
We render the item.question
and item.answer
values from the object entry.
And we have a button to let us delete the item with the deleteItem
method.
deleteItem
takes the index of the item to delete.
The key
prop lets us set the unique ID for the item so that Vue 3 can keep track of the rendered array items properly.
The data
method returns an object with the initial values of the reactive properties.
The add
method calls push
with an object to add an item to the array.
We merge the id
with the other this.item
properties to form the final object before pushing it.
deleteItem
calls splice
with the index
and 1 to delete an item with the given index and deletes 1 item only.
Now we see that the list is displayed when we type in something and click submit.
Conclusion
We can create our own flashcard app easily with Vue 3 and JavaScript.