Categories
Vue 3 Projects

Create a Voting App with Vue 3 and JavaScript

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 voting 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 voting-app

and select all the default options to create the project.

Create the Voting App

To create the voting app, we write:

<template>
  <form>
    <div>
      <label>What's your favorite fruit?</label>
      <input type="radio" value="apple" v-model="choice" /> apple
      <input type="radio" value="orange" v-model="choice" /> orange
      <input type="radio" value="grape" v-model="choice" /> grape
    </div>
    <button type="button" @click="vote">vote</button>
  </form>
  <div>
    <h1>result</h1>
    <p v-for="(value, key) of results" :key="key">{{ key }}: {{ value }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      choice: "",
      results: {},
    };
  },
  methods: {
    vote() {
      if (!localStorage.getItem("vote-result")) {
        localStorage.setItem("vote-result", JSON.stringify({}));
      }
      const { choice } = this;
      const results = JSON.parse(localStorage.getItem("vote-result"));
      if (!Object.prototype.hasOwnProperty.call(results, choice)) {
        results[choice] = 0;
      }
      results[choice]++;
      localStorage.setItem("vote-result", JSON.stringify(results));
      this.results = JSON.parse(localStorage.getItem("vote-result"));
    },
  },
};
</script>

In the template, we have the form with radio buttons that binds to the choice reactive property with v-model .

The vote button runs the vote method when it’s clicked.

The div renders the choices and the number of votes for each.

value has the number of votes.

key has the choice name.

In the script tag, we have the data method that returns the reactive properties we’re using.

In the vote method, we check if the local storage result with key vote-result exists.

If it doesn’t we call setItem to add the entry.

Then we get the result by calling getItem with vote-result and parse the returned string with JSON.parse .

Then we check if the choice exists in the result.

If Object.prototype.hasOwnProperty.call(results, choice) returns true , then the property for the choice exists in results .

If it doesn’t, we add the property and set it to 0.

And then we increment the property’s value by 1 to register the vote.

Then we call setItem to update the local storage entry.

And then we get it and parse it again and assign that to this.results to update it.

Conclusion

We can create a voting app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Drawing App with Vue 3 and JavaScript

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 drawing 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 drawing-app

and select all the default options to create the project.

Create the Drawing App

To create the drawing app, we write:

<template>
  <canvas
    ref="canvas"
    @mousemove="draw"
    @mousedown="setPosition"
    @mouseenter="setPosition"
    @resize="resize"
    id="canvas"
  ></canvas>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      pos: {},
    };
  },
  methods: {
    setPosition(e) {
      this.pos.x = e.clientX;
      this.pos.y = e.clientY;
    },
    resize() {
      const { canvas } = this.$refs;
      const ctx = canvas.getContext("2d");
      ctx.canvas.width = window.innerWidth;
      ctx.canvas.height = window.innerHeight;
    },
    draw(e) {
      if (e.buttons !== 1) {
        return;
      }
      const { canvas } = this.$refs;
      const ctx = canvas.getContext("2d");
      const { pos } = this;
      ctx.beginPath();
      ctx.lineWidth = 5;
      ctx.lineCap = "round";
      ctx.strokeStyle = "green";
      ctx.moveTo(pos.x, pos.y);
      this.setPosition(e);
      ctx.lineTo(pos.x, pos.y);
      ctx.stroke();
    },
  },
};
</script>

<style scoped>
#canvas {
  border: 1px solid black;
}
</style>

In the template, we add the canvas element.

We assign it a ref so that we can access the component code.

Also, we add a few event listeners to the canvas.

mousemove listens to mouse movements and draw on the canvas when we move the mouse.

mousedown and mouseenter events are triggered when we click on a mouse button or enter the canvas respectively, so we set the position to start drawing the line.

The resize event is triggered when we change the screen size, and we need to listen to that to change the canvas size to match the screen.

In the script tag, we have the data method that returns the pos reactive property that we use to store the mouse position.

The setPosition method sets this.pos to the current position of the mouse.

The resize method gets the canvas and set the width and height of the canvas respectively.

We resize it so that the mouse position matches the canvas position when we draw.

The draw method does the drawing.

We only draw when we click on the left mouse button, and we check that by checking if e.buttons is 1.

Then we get the canvas and the mouse position from this.pos .

We call beginPath to start drawing.

lineWidth sets the line width.

lineCap sets the line end style.

strokeStyle sets the color of the line.

moveTo moves the cursor to the given position.

lineTo draws the line to the given position.

stroke renders the line drawn.

In the style tag, we set the border so that we can see where the canvas is.

Conclusion

We can create a drawing app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Currency Converter with Vue 3 and JavaScript

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 currency converter 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 currency-converter

and select all the default options to create the project.

Create the Currency Converter

To create the currency converter, we write:

<template>
  <form @submit.prevent="convert">
    <div>
      <label>value</label>
      <input v-model.number="value" />
    </div>
    <div>
      <label>from currency</label>
      <select v-model="fromCurrency">
        <option v-for="c of fromCurrencies" :key="c">{{ c }}</option>
      </select>
    </div>
    <div>
      <label>to currency</label>
      <select v-model="toCurrency">
        <option v-for="c of toCurrencies" :key="c">{{ c }}</option>
      </select>
    </div>
    <button type="submit">convert</button>
  </form>
  <div>
    {{ value }} {{ fromCurrency }} is {{ result.toFixed(2) }} {{ toCurrency }}
  </div>
</template>

<script>
const currencies = ["EUR", "USD", "CAD"];
export default {
  name: "App",
  data() {
    return {
      value: 0,
      fromCurrency: "",
      toCurrency: "",
      currencies,
      result: 0,
    };
  },
  computed: {
    fromCurrencies() {
      const { toCurrency, currencies } = this;
      return currencies.filter((c) => c !== toCurrency);
    },
    toCurrencies() {
      const { fromCurrency, currencies } = this;
      return currencies.filter((c) => c !== fromCurrency);
    },
    formValid() {
      const { value, fromCurrency, toCurrency } = this;
      return +value >= 0 && fromCurrency && toCurrency;
    },
  },
  methods: {
    async convert() {
      const { fromCurrency, toCurrency, value, formValid } = this;
      if (!formValid) {
        return;
      }
      const res = await fetch(
        `https://api.exchangeratesapi.io/latest?base=${fromCurrency}`
      );
      const { rates } = await res.json();
      this.result = value * rates[toCurrency];
    },
  },
};
</script>

We have a form that has an input to enter the value of the currency to convert form.

The from currency dropdown lets us choose the currency to convert from.

And the to currency dropdown lets us choose the currency to convert to.

We bind all the values from the input and select dropdowns to reactive properties with v-model .

The @submit directive listens to the submit event which is emitted when we click convert.

The prevent modifier lets us do client-side form submission.

In the script tag, we have the currencies array with the currencies list.

The data method returns the reactive properties we use.

The fromCurrencies computed property has the list of currencies we can convert from.

We filter out the one that we chose in the to currency dropdown.

The toCurrencies dropdown is similarly used for the to currency dropdown and filters out the choice chosen in the from currency dropdown.

The formValid computed property checks if value is bigger than or equal to 0.

The convert method gets the exchange rate from the free Foreign exchange rates API.

The base query parameter sets the currency to convert from.

We get the rates with fetch and use that to compute the result.

Conclusion

We can create a currency converter easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Recipe App with Vue 3 and JavaScript

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.

Categories
Vue 3 Projects

Create a PIN Pad with Vue 3 and JavaScript

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 PIN pad 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 pin-pad

and select all the default options to create the project.

Create the PIN Pad

To create the PIN pad, we write:

<template>
  <div>{{ pin }}</div>
  <div>
    <div>
      <button @click="pin += '1'">1</button>
      <button @click="pin += '2'">2</button>
      <button @click="pin += '3'">3</button>
    </div>
    <div>
      <button @click="pin += '4'">4</button>
      <button @click="pin += '5'">5</button>
      <button @click="pin += '6'">6</button>
    </div>
    <div>
      <button @click="pin += '7'">7</button>
      <button @click="pin += '8'">8</button>
      <button @click="pin += '9'">9</button>
    </div>
    <div>
      <button @click="pin = pin.slice(0, pin.length - 1)">&lt;</button>
      <button @click="pin += '0'">0</button>
      <button @click="pin = ''">C</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      pin: "",
    };
  },
};
</script>

We display the pin at the top of the template.

Then we add buttons into the div.

In the number keys, we have the @click directive to append the corresponding characters to pin .

The backspace (<) button calls slice to return the pin string without the last character and assign it to pin .

And the C key clears the pin by assigning it to an empty string.

Now when we click on the keys, we see the PIN update.

Conclusion

We can create our own PIN pad easily with Vue 3 and JavaScript.