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 weather 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 weather-app
and select all the default options to create the project.
Create the Weather App
To create the weather app, we write:
<template>
<form @submit.prevent="getWeather">
<div>
<label>city</label>
<input v-model.trim="city" />
</div>
<button type="submit">get weather</button>
</form>
<div>
<p>feels like: {{ result.feels_like }}</p>
<p>humidity: {{ result.humidity }}</p>
<p>pressure: {{ result.pressure }}</p>
<p>temperature: {{ result.temp }}</p>
<p>high: {{ result.temp_max }}</p>
<p>low: {{ result.temp_min }}</p>
</div>
</template>
<script>
const APIKEY = "your-key";
export default {
name: "App",
data() {
return {
city: "",
result: {},
};
},
methods: {
async getWeather() {
if (!this.city) {
return;
}
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${APIKEY}`
);
const { main } = await res.json();
this.result = main;
},
},
};
</script>
We have a form with an input that lets us enter the city.
We bind the inputted value to the city
reactive property with v-model
.
The trim
modifier lets us remove the leading and trailing whitespace with the inputted value.
The @submit
directive lets us listen to the submit event which is triggered when we click the get weather button.
prevent
lets us prevent server-side submission and do a client-side submission.
Below that, we display the result from the response.
In the script tag, we have the data
method to return reactive properties.
The getWeather
method calls fetch
to make a request to the Open Weather Map API to get the weather data based on the entered city
.
And then we call res.json
to convert the response to a JavaScript object.
Finally, we assign that to this.result
so we can display it in the template.
Conclusion
We can create a weather app easily with Vue 3 and JavaScript.