Categories
Vue 3 Projects

Create a Tip Calculator 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 tip calculator 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 tip-calculator

and select all the default options to create the project.

Create a Tip Calculator App

To create the tip calculator app, we write:

<template>
  <form @submit.prevent="calculate">
    <div>
      <label>bill amount</label>
      <input v-model.number="billAmount" />
    </div>

    <div>
      <label>percentage tip</label>
      <input v-model.number="percentageTip" />
    </div>

    <button type="submit">calculate</button>
  </form>
  <p>tip amount: {{ tipAmount.toFixed(2) }}</p>
  <p>total: {{ total.toFixed(2) }}</p>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      billAmount: 0,
      percentageTip: 0,
      tipAmount: 0,
      total: 0,
    };
  },
  computed: {
    formValid() {
      const { billAmount, percentageTip } = this;
      return +billAmount > 0 && +percentageTip > 0;
    },
  },
  methods: {
    calculate() {
      const { billAmount, percentageTip } = this;
      this.tipAmount = billAmount * (percentageTip / 100);
      this.total = billAmount * (1 + percentageTip / 100);
    },
  },
};
</script>

We add a form element into the template.

Then we listen to the submit event with the @submit directive.

prevent lets us stop server-side form submission and do client-side form submission instead.

Inside the form, we have inputs to let us enter bill amount and percentage tip.

The v-model directive lets us bind the entered value to a reactive property.

number lets us convert the entered value to a number automatically.

Then we show tipAmount and total .

toFixed converts the numbers to 2 decimal places.

In the component object, we return an object with the initial values of the reactive properties in the data method.

We check if the entered values are valid with the formValid reactive property.

In it, we check if billAmount and percentageTip are bigger than 0.

And in the calculate method, we get the billAmount and percentageTip and calculate the tipAmount and total .

They’re converted to numbers automatically with number so we don’t have to convert them again.

And we already know the values are valid, so they must be numbers.

Now when we type in the values and click calculate, we see the tip amount and total.

Conclusion

We can create a tip calculator 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 *