Categories
Vue 3 Projects

Create a BMI 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 BMI 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 bmi-calculator

and select all the default options to create the project.

Create the BMI Calculator App

To create the BMI calculator, we write:

<template>
  <form @submit.prevent="calculate">
    <div>
      <label>height in meters</label>
      <input v-model.number="height" />
    </div>

    <div>
      <label>mass in kg</label>
      <input v-model.number="mass" />
    </div>

    <button type="submit">calculate</button>
  </form>
  <p>bmi: {{ bmi }}</p>
</template>

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

We create a form and add the submit event listener with the @submit directive.

prevent lets us do client-side submission instead of server-side submission.

Then we add the input boxes into the divs.

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

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

In the component object, we have the data method.

It returns an object with the height , mass and bmi reactive properties.

Then we create the formValid computed property to check if the enteredheight and mass are bigger than 0.

We use this in the calculate method to check if the entered values are valid.

If they are, then we compute the bmi with the height and mass .

The ** operator is the exponentiation operator.

Conclusion

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