2👍
✅
You should assign the response value to the weather property directly like this.
methods: {
async getWeather() {
let self = this;
try {
const response = await fetch('https://api.weatherbit.io/v2.0/current?city=Berlin&country=DE&key=dcbea1b771ab41f09cd6b138d8cd50c2');
const myJson = await response.json();
self.weather = myJson.data[0].temp;
console.log(self.weather);
} catch (error) {
console.error(error);
}
}
}
Here is the working example.
1👍
I think you should insert your logic inside mounted() , not in created() , this should fix your problem with rendering.
<template>
<div>
<h1>Weather</h1>
{{ weather }}
</div>
</template>
<script>
export default {
name: 'Weather',
data() {
return {
weather : {},
}
},
mounted() {
this.getWeather()
},
methods: {
async getWeather() {
let self = this;
try {
const response = await fetch('https://api.weatherbit.io/v2.0/current?city=Berlin&country=DE&key=dcbea1b771ab41f09cd6b138d8cd50c2');
const myJson = await response.json();
self.weather.temp = myJson.data[0].temp;
self.weather.sensation = myJson.data[0].app_temp;
self.weather.description = myJson.data[0].weather.description;
} catch (error) {
console.error(error);
}
}
</script>
These are the steps in Vue lifecycle :
beforCreate,
created,
beforeMount,
mounted,
beforeUpdate,
updated,
beforeDestroy,
destroyed
Hope this will help you to understand Vue lifecycle 🙂
Source:stackexchange.com