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 temperature converter 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 temperature-converter
and select all the default options to create the project.
Create the Temperature Converter
To create the temperature converter, we write:
<template>
<form @submit.prevent="convert">
<div>
<label>temperature in celsius</label>
<input v-model.number="celsius" />
</div>
<button type="submit">convert</button>
</form>
<div>{{ celsius }}c is {{ fahrenheit }}f</div>
</template>
<script>
export default {
name: "App",
data() {
return {
celsius: 0,
fahrenheit: 0,
};
},
computed: {
formValid() {
return !isNaN(+this.celsius);
},
},
methods: {
convert() {
if (!this.formValid) {
return;
}
this.fahrenheit = this.celsius * (9 / 5) + 32;
},
},
};
</script>
We create the form with an input that takes the temperature in celsius.
We bind the input value to the celsius
reactive with v-model
.
The number
modifier lets us convert it to a number automatically.
In the form
, we add the @submit
directive to listen for clicks on the button with type submit
.
The prevent
modifier prevents server-side submissions and lets us do client-side submissions.
Then in the component object, we have the data
method that returns the celsius
and fahrenheit
reactive properties.
We have the formValid
computed property that checks if the celsius
reactive property is a number.
Then in the convert
method,. we check the formValid
computed property to see if the form is valid.
Then if it is, we compute the fahrenheit
value from the celsius
value.
And finally, in the template, we display the results of the convert in the div.
Conclusion
We can create a temperature easily with Vue 3 and JavaScript.