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 recipe 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 recipe-app
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 Recipe App
To create the recipe app, we write:
<template>
<form @submit.prevent="addRecipe">
<div>
<label>name</label>
<input v-model="recipe.name" />
</div>
<div>
<label>ingredients</label>
<textarea v-model="recipe.ingredients"></textarea>
</div>
<div>
<label>steps</label>
<textarea v-model="recipe.steps"></textarea>
</div>
<button type="submit">add recipe</button>
</form>
<div v-for="(r, index) of recipes" :key="r.id">
<h1>{{ r.name }}</h1>
<h2>ingredients</h2>
<div class="content">{{ r.ingredients }}</div>
<h2>steps</h2>
<div class="content">{{ r.steps }}</div>
<button type="button" @click="deleteRecipe(index)">delete</button>
</div>
</template>
<script>
import { v4 as uuidv4 } from "uuid";
export default {
name: "App",
data() {
return {
recipe: {
name: "",
ingredients: "",
steps: "",
},
recipes: [],
};
},
computed: {
formValid() {
const { name, ingredients, steps } = this.recipe;
return name && ingredients && steps;
},
},
methods: {
addRecipe() {
if (!this.formValid) {
return;
}
this.recipes.push({
id: uuidv4(),
...this.recipe,
});
},
deleteRecipe(index) {
this.recipes.splice(index, 1);
},
},
};
</script>
<style scoped>
.content {
white-space: pre-wrap;
}
</style>
In the template, we have a form that has the name, ingredients, and steps fields.
We bind the values inputted into the input or textarea with v-model
to reactive properties.
The @submit
directive lets us submit the form when the add recipe button is clicked.
prevent
lets us do client-side form submission instead of server-side.
Below that, we have divs that renders the recipes added with v-for
.
We’ve to set the key
prop to a unique ID so that Vue 3 can identify the rendered items.
Inside the div, we display the content added, and a button that calls deleteRecipe
when we click it to delete an entry.
In the script tag, we have the data
method that returns the reactive properties we use.
The formValid
reactive property checks whether each field is filled in.
The addRecipe
method checks the formValid
reactive property to see if the form is valid.
Then we call push
if it is to add an entry to the recipes
array.
The uuidv4
function generates a unique ID for the entry.
The deleteRecipe
method calls splice
to remove the entry with the given index.
In the style tag, we have white-space: pre-wrap;
applied to preserve whitespace in the divs with the given class.
Conclusion
We can create a recipe app easily with Vue 3 and JavaScript.