How to Make a Simple Unit Converter in Vue
Tags: vue, javascript, webdev, beginners
Published: 2022-03-25 15:25:50

This article is a collaboration with [UPDIVISION](https://updivision.com/), an outsourcing company building complex software for companies all over the world.

_**Read the [original article](https://updivision.com/blog/post/how-to-make-a-simple-unit-converter-in-vue) on their blog**_

In this article, you’ll be learning how to create an energy unit converter SPA(Single Page Application) in Vue!

##What You Will Learn

This is a simple, intuitive project, which makes it perfect for beginners. By building this as a Vue beginner, you will learn how to:

1. Process user input through Vue
2. Perform mathematical operations on user input and store the output as a variable
3. Manipulate the DOM(Document Object Model)
4. Use functions in Vue
5. Use buttons in Vue

##The End Result

Here’s how the app you’ll be making in this tutorial will work:
![](https://lh4.googleusercontent.com/eiCRAwJEwkiTD1cLMsFxLZEVK24uHwQjJAsDiI2l9LbALsPUS1tQFQ0mtjQxHOzobMM02aOPhOVk94-yzn3ZFIJ2VbBt9Z-agWJK-Scy55pAHfKjGLHBCVTcIatu_TswUgu59l_I)

##Setup

First, and foremost, install the Vue CLI through npm or yarn if you haven’t already.

```bash

npm install -g @vue/cli

```

Or

```bash

yarn global add @vue/cli

```

Next, create a new Vue project by running the following.

```bash

npm init vue@latest

```

You will be presented with the following prompts:

```bash

✔ Project name: … your-project-name>

✔ Add TypeScript? …No / Yes

✔ Add JSX Support? …No / Yes

✔ Add Vue Router for Single Page Application development? …No / Yes

✔ Add Pinia for state management? …No / Yes

✔ Add Vitest for Unit testing? …No / Yes

✔ Add Cypress for both Unit and End-to-End testing? …No / Yes

✔ Add ESLint for code quality? …No / Yes

✔ Add Prettier for code formating? …No / Yes

```

Simply name your Vue project, and choose any additional settings if you want, but that’s not necessary. After that’s done, `cd` into your new Vue project and install npm:

```bash

cd your <project name>

```

then

```bash

npm install

```

##Making a Simple Energy Unit Converter

When you open your new project’s directory in your editor of choice, you’ll see the following structure:

![](https://lh6.googleusercontent.com/KZU2GNKkkdManXedGAsxHG2fdcN4Cf8neueGVCRC5iVzvVjLau9Rsi8szqhATVz1Jqu51Oxoc7tO_NXDFs6oe8XZfszX7xIF6Nx0R5iW8TdK1mwbXxCJ83MgnJPPZYGkZsl3kuFH)

Open the _src_ directory inside your new Vue project, open the _App.vue_ file and remove all of _App.vue_’s current contents so that the file is empty.

Now, to make a simple energy unit converter, first add a script section and a template section into your _App.vue_ like so:

```vue

<script>

</script>

<template>

</template>

```

Before we add the javascript that is going to transform units inputted by the user, we need to add input elements into the template section. They are going to pass their values to the javascript functions that are going to do the conversions.

```vue

<script>

</script>

<template>

<input type="number" :value="j" @change="setJoules"> Joules =

<input type="number" :value="kc" @change="setCalories"> Calories

</template>

```

The `:value` attribute specifies the variable in which values entered into the input elements will be stored.

Now if you run `npm run dev` in your Vue project’s directory, you should see the following terminal output:

![](https://lh4.googleusercontent.com/dKccQhTffU_HrpX4jSYZ-g2onjvv9XDXjHDiYyN1PtPXTYR7GJBCHd4Lgpm-XF6scvGbMueJbt8V3Js2G6X_g86fo38GCBGC8K3eJc_hKTs7wBNqQT3wMdsJ8fmXTjVhJPJ3Q3yW)

Open a browser tab on the localhost specified in the terminal output and you should see the input elements displayed by your Vue app:

![](https://lh4.googleusercontent.com/rYKxfRe0S11p7Ng5uMIdspcBeKDf-BXNEPXBR7VYPQ9eXKZ2qvX7ub3cIckJgKfnfar6lTluObIiLrL0clE9SORAsbE5jT8ve6e8aLmThonYY9pbkGfD-vabtj4bCLZXtVWzis6h)

###Adding the Javascript

You’ll soon notice that if you enter values into the input elements, nothing happens. So, let’s add the javascript to make the unit converter work!

First add the following to your script section.
```javascript
export default {
    data() {
        return {
        }
    },
}
```


Inside the `data()` function, we will define the variables that we’ll be using in our energy unit converter as well as give them their default values.
```javascript
export default {
    data() {
        return {
            j: 1,
            kc: 4.2
        }
    },
}
```

After adding this, your input elements should look like this:

![](https://lh4.googleusercontent.com/8gMVFzNOAhWPziTKbMEWUn77ykdhB6cpFP31kf_BvVUCr3e_1p7PEp_c8A93-TYWxAlC6hWGSJnnIBF-ng-W3d_cJTzXzr7SuYw8-1B0HVs1AZdWpvjMHsRqr18UvkcglfNos24v)

Now, to make the functions that are going to convert values from the input elements, add a `methods` sub-section into your script section under the `data` sub-section like so:
```javascript
export default {
    data() {
        return {
            j: 1,
            kc: 4.2
        }
    },
    methods: {
    }
}
```

Now it’s time to add the javascript functions that are going to convert values entered into the input elements. Each input element takes in different unit types. In this example, the first input element takes in Joules while the second one takes in Calories.

You’ve probably noticed that each input element references a function through a `@change` attribute. These functions will take in the values entered into the input elements stored in the `j` and `kc` variables and convert them into the unit represented by the other input element.

Let’s define the first input element’s function: setJoules. Here’s how it’s going to look:
```javascript
setJoules(e, j = +e.target.value) {
    this.j = j
    this.kc = (j*4.2).toFixed(2)
},
```

Here’s what this function does:

1. It takes in the `j` variable.
2. It defines the `j` variable.
3. It sets the variable associated with the other input element(kc) as `j*4.2` and rounds the value to 2 decimal places.

Now here’s how the function referenced by the other input element is going to look:

```javascript
setCalories(e, kc = +e.target.value) {
    this.kc = kc
    this.j = (kc/4.2).toFixed(2)
},
```


As you can see, it works similarly to the first function but this time with the `kc` variable.

Here’s how your `App.vue` should look so far:
```vue
<script>
export default {
    data() {
        return {
            j: 1,
            kc: 4.2
        }
    },
    methods: {
        setJoules(e, j = +e.target.value) {
            this.j = j
            this.kc = (j*4.2).toFixed(2)
        },
        setCalories(e, kc = +e.target.value) {
            this.kc = kc
            this.j = (kc/4.2).toFixed(2)
        },
    }
}
</script>

<template>
<input type="number" :value="j" @change="setJoules"> Joules =
<input type="number" :value="kc" @change="setCalories"> Calories
</template>
```

Now if you open your Vue app in a browser, you will see that your input elements are able to convert their inputted values:

![](https://lh6.googleusercontent.com/MNI2P9PNUJ_s9JXNa2y45xhKKCDSv512Yb1OAIMGM9eQcJ78BRPcyC0vT3nzDW-qqKfoOiAqBTTDOdaiowwVnY0nBG1e75Lgx_kReU-6LgRagGw5tongBAnxxpcB8I7VQZDH2EsO)

As you can see, your app can convert values from Joules to Calories and vice-versa!

###Changing the Input Elements

This little app is quite useful when you want to convert Joules to Calories and vice versa, but what if you want the possibility to convert Joules to another value? In this case, we’ll need to introduce another input element. For this energy converter app, let’s add an input element that will take in and display values in KWh(Kilowatt Hours), another popular measurement of energy:

```vue

<input type="number" :value="kwh" @change="setKWh"> KWh

```

We need to put this input element inside of the following div element:

```vue

<div v-if="b1 == 1" style="display: inline-block;">

</div>

```

Then we need to put our existing “Calories” input element into the following div:

```vue

<div v-if="b1 == 0" style="display: inline-block;">

</div>

```

You will see why this is necessary in a minute.

We will then have to define the `kwh` variable inside the `data()` function:
```javascript
data() {
    return {
        j: 1,
        kc: 4.2,
        kwh: 0
    }
},
```

Next, you’ll need to create the `setKWh()` function:
```javascript
setKWh(e, kwh = +e.target.value) {
    this.kwh = kwh
    this.j = (kwh/(2.777778*10**-7)).toFixed(2)
},

```

Finally, you’ll need to add the following method into the `setJoules()` function:
```javascript
setJoules(e, j = +e.target.value) {
    this.j = j
    this.kc = (j*4.2).toFixed(2)
    this.kwh = (j*(2.777778*10**-7)).toFixed(10)
},
```

1 KWh is 3600000 joules, a pretty large difference, so in order for the conversions to be accurate, we need to round the value in KWh to 10 decimal places.

Here’s how your `App.vue` should look like so far:
```vue
<script>
export default {
    data() {
        return {
            j: 1,
            kc: 4.2,
            kwh: 0
        }
    },
    methods: {
        setJoules(e, j = +e.target.value) {
            this.j = j
            this.kc = (j*4.2).toFixed(2)
            this.kwh = (j*(2.777778*10**-7)).toFixed(10)
       },
        setCalories(e, kc = +e.target.value) {
            this.kc = kc
            this.j = (kc/4.2).toFixed(2)
        },
       setKWh(e, kwh = +e.target.value) {
            this.kwh = kwh
            this.j = (kwh/(2.777778*10**-7)).toFixed(2)
        }
    }
}
</script>

<template>
<input type="number" :value="j" @change="setJoules"> Joules =
<div v-if="b1 == 0" style="display: inline-block;">
    <input type="number" :value="kc" @change="setCalories"> Calories
</div>
<div v-if="b1 == 1" style="display: inline-block;">
    <input type="number" :value="kwh" @change="setKWh"> KWh
</div>
</template>
```

By looking at the divs containing the input elements, you’re probably wondering what the `v-if` attribute does. The answer is pretty simple: the `v-if` attribute sets a condition for displaying elements. For example, the first container div only renders its input element when `b1 == 0` while the second div only renders its input element when `b1 == 1`. The purpose of this is to give the user the ability to switch between input elements (Calories and KWh) by changing the `b1` variable.

How are they going to do that? Using this button(the br elements put the button underneath the inputs to look neater):
```vue
<br><br>
<button @click="setB">
    Change Unit
</button>
```
Which when clicked, will trigger the `setB()` function through the `@click` attribute:
```javascript
setB(){
    if(this.b1 < 1){
        this.b1 += 1
    }
    else{
        this.b1 = 0
    }
}

```

As you can see, the `setB()` function increments `b1` when its value is lower than 1, and sets its value to 0 when its value is 1.

Don’t forget to define the `b1` variable and set it’s default value to “0” so that the “Calories” input element gets rendered by default:
```javascript
data() {
    return {
        j: 1,
        kc: 4.2,
        kwh: 0,
        b1: 0
    }
},
```

Here’s how your _App.vue_ should look so far:
```vue
<script>
export default {
    data() {
        return {
            j: 1,
            kc: 4.2,
            kwh: 0,
            b1: 0
        }
    },
    methods: {
        setJoules(e, j = +e.target.value) {
            this.j = j
            this.kc = (j*4.2).toFixed(2)
            this.kwh = (j*(2.777778*10**-7)).toFixed(10)
       },
        setCalories(e, kc = +e.target.value) {
            this.kc = kc
            this.j = (kc/4.2).toFixed(2)
        },
       setKWh(e, kwh = +e.target.value) {
            this.kwh = kwh
            this.j = (kwh/(2.777778*10**-7)).toFixed(2)
        },
        setB(){
            if(this.b1 < 1){
                this.b1 += 1
            }
            else{
                this.b1 = 0
            }
        }
    }
}
</script>

<template>
<input type="number" :value="j" @change="setJoules"> Joules =
<div v-if="b1 == 0" style="display: inline-block;">
    <input type="number" :value="kc" @change="setCalories"> Calories
</div>
<div v-if="b1 == 1" style="display: inline-block;">
    <input type="number" :value="kwh" @change="setKWh"> KWh
</div>
<br><br>
<button @click="setB">
    Change Unit
</button>
</template>
```

Now if you open your Vue app in a browser, you should be able to play around with your working energy unit converter app:

![](https://lh3.googleusercontent.com/W-g_TP9UVECRVZ1ufOOUX4eGiGJPQV4WCGcvb3iejK60mLaSn3M1FA8DxJ-vg4wHspyU3u55HVcxIOCwruixDQk_wOEwdeNEGWja5MPkHnNoLSb-5AIziYshEtvnD_GztycbgVZ4)

##Conclusion

Congratulations! Now you have a functioning unit converter. You can add more units into your app by following what I’ve shown with the `Calories` and `KWh` inputs.

Using what’s shown in this article, you can also make a converter around other unit types such as: distance, mass and temperature.

I hope that you found this beginner Vue project useful and fun!

To find out more about code, the software development process, or to have awesome apps built for your business needs - contact [UPDIVISION](https://updivision.com/).