从API提取后,我在更新DOM时遇到麻烦。
我的对象正确地获取了数据,但是DOM之前已经呈现过,并且在收到API数据后它不会更新,我似乎无法理解为什么不更新自身。
这是我的代码:
<template>
<div>
<h1>Weather</h1>
{{ weather }}
</div>
</template>
<script>
export default {
name: 'Weather',
data() {
return {
weather : {},
}
},
created() {
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>
我认为您应该将逻辑插入Mounted()而不是created()中,这应该可以解决渲染问题。