问题描述
我正在尝试使用 JSON 对象获取 ID:
"object1":
[
{"name":"Station A","cycleTime":5,"object2":{"id":"60","time":032820200122}}
],
此对象在 Visual Studio Code 上的 json-server 中运行
Vue.js 代码:
<template>
<div>
<div v-for="object1 in stations" :key="object1">
<h1>{{object1.object2.id}}</h1>
</div>
</div>
</template>
<script>
export default {
name: 'app',data() {
return {
stations: [],}
},mounted() {
fetch("http://localhost:8000/station")
.then(res => res.json())
.then(data => this.station = data)
.catch(err => console.log(err.message))
},}
</script>
我正在尝试从第二个对象获取 id 数据,但是当我在控制台 apiary 中运行 json-server 时出现以下错误
TypeError:无法读取 null 的属性“id”
解决方法
错误在以下函数中:您正在使用 this.station
mounted() {
fetch("http://localhost:8000/station")
.then(res => res.json())
.then(data => this.station = data)
.catch(err => console.log(err.message))
},
但是你的数据数组是站。这是一个拼写错误。请使用这个
mounted() {
fetch("http://localhost:8000/station")
.then(res => res.json())
.then(data => this.stations = data)
.catch(err => console.log(err.message))
},
,
确保代码片段中的所有变量名称都是正确的
<template>
<ul id="example-2">
<li v-for="(item,index) in stations" :key="index">
<h1>{{item.object2.id}}</h1>
</li>
</ul>
</template>
<script>
export default {
name: 'app',data () {
return {
stations: [
{
name: 'Station A',cycleTime: 5,object2: {
id: '60',time: 032820200122
}
}
]
}
},mounted () {
// please make sure after the api call value is assigned to this.stations
// also the response should have similar structure to the above initial structure
}
}
</script>