尝试从 API 动态呈现天气信息。 API 请求正在返回我可以在日志和页面上显示的数据。但是,当我尝试显示响应数组中的单个项目时,Web 控制台报告它无法读取未定义的属性(读取“0”)。然后整个页面将停止渲染。
代码
<script>
import axios from 'axios'
export default{
data() {
return {
weather: []
};
},
async created(){
try{
const response = await axios.get('apilinkredacted');
this.weather = response.data.daily;
console.log(this.weather)
} catch (error) {
console.error(error);
}
}
}
</script>
<template>
<main>
<div v-for="n in 4" class="text-cliPurple border-t border-windowOutline pb-2 pl-2">
<!-- weather.daily.temperature_2m_max[n-1] -->
<p class="underline">{{ weather.time[n-1] }}</p>
<div class="grid grid-cols-2">
<div class="">
<pre>
\ /
.-.
― ( ) ―
`-’
/ \
</pre>
</div>
<div class="text-left">
<p><span class="text-cliOrange">Temp:</span> {{ weather.temperature_2m_max[n-1] }} C</p>
<p><span class="text-titleColor">Rain Chance:</span> {{ weather.precipitation_probability_max[n-1] }}%</p>
<p><span class="text-userColor">Rain Amount:</span> {{ weather.rain_sum[n-1] }}mm</p>
<p><span class="text-cliRed">UV:</span> {{ weather.uv_index_max[n-1] }}</p>
</div>
</div>
</div>
</main>
</template>
JSON 响应
{
"latitude": -35.25,
"longitude": 149.125,
"generationtime_ms": 0.06699562072753906,
"utc_offset_seconds": 36000,
"timezone": "Australia/Sydney",
"timezone_abbreviation": "AEST",
"elevation": 568,
"daily_units": {
"time": "iso8601",
"temperature_2m_max": "°C",
"apparent_temperature_max": "°C",
"uv_index_max": "",
"rain_sum": "mm",
"precipitation_probability_max": "%"
},
"daily": {
"time": [
"2024-05-09",
"2024-05-10",
"2024-05-11",
"2024-05-12",
"2024-05-13",
"2024-05-14",
"2024-05-15"
],
"temperature_2m_max": [
16.5,
14.9,
13.1,
13.4,
17.5,
15.9,
14.7
],
"apparent_temperature_max": [
14.4,
13.2,
11.4,
11.1,
16,
14.6,
13.8
],
"uv_index_max": [
1.95,
2.55,
0.6,
3.9,
4.2,
3.95,
3.65
],
"rain_sum": [
0,
5.1,
26.5,
3.7,
0,
0,
0
],
"precipitation_probability_max": [
52,
74,
90,
37,
0,
0,
3
]
}
}
我最初认为这是因为该项目不是数组,但是当我使用 console.log(this.weather.time[0]) 时,我在 Web 控制台中打印了正确的数据。如果我不指定特定项目,我可以多次渲染整个响应,但是当我添加细节并重新加载时,整个页面会变成空白。
此外,当我通过 Get 请求存储单个数组时
this.weather = response.data.daily.time;
我可以使用 weather[0]
来处理单个项目,并且它显示没有问题。
您正在尝试访问尚不存在的数据。 你有两个选择
使用? (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
{{时间?.时间[n-1] }}2),在代码中引入 v-if
<template>
<main v-if="Object.keys(weather).length>0">
<div v-for=‘n in 4’ class=‘text-cliPurple border-t border-windowOutline pb-2 pl-2’>
...
另一方面,你也犯了一些错误。 首先,天气数据类型是 [],但是当您在创建的方法中设置它时,您会传递一个 {}。 第二是你应该避免通过索引访问数据