Categories
Vue 3 Projects

Create a Voting App with Vue 3 and JavaScript

Spread the love

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.

Leave a Reply

Your email address will not be published. Required fields are marked *