Categories
Vue 3 Projects

Create a Percentage Calculator 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 percentage calculator 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 percentage-calculator

and select all the default options to create the project.

Create the Percentage Calculator

To create the percentage calculator, we write:

<template>
  <form @submit.prevent="calculate">
    <div>
      <label>points given</label>
      <input v-model.number="pointsGiven" />
    </div>

    <div>
      <label>points possible</label>
      <input v-model.number="pointsPossible" />
    </div>
    <button type="submit">calculate</button>
  </form>
  <div>percentage:{{ percentage }}</div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      pointsGiven: 0,
      pointsPossible: 0,
      percentage: 0,
    };
  },
  computed: {
    formValid() {
      const { pointsGiven, pointsPossible } = this;
      return +pointsGiven >= 0 && +pointsPossible > 0;
    },
  },
  methods: {
    calculate() {
      if (!this.formValid) {
        return;
      }
      const { pointsGiven, pointsPossible } = this;
      this.percentage = (pointsGiven / pointsPossible) * 100;
    },
  },
};
</script>

We have a form that has the @submit directive to let us listen to the submit event emitted when clicking the button with type submit .

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

Then we have the inputs for entering the points given and points possible values.

We bind the inputted values to reactive properties with the v-model directive.

The number modifier converts the inputted values to numbers automatically.

Then we have the calculate button which we click to submit the form.

Below that, we have the div to display the calculated percentage .

In the component object, we have the data method to return an object with the reactive properties and their initial values.

In the formValid computed property, we check if pointsGiven and pointsPossible are valid values.

pointsPossible should be bigger than 0 since we can’t divide by 0.

Then below that, we have the calculate method, which checks if the formValid property is true .

If it’s true , then we calculate the percentage.

Conclusion

We can create a percentage calculator easily with Vue 3 and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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