javascript - 可以像这样访问 JSON 对象内部的数据集合,例如。使用 Vue.js 的 object1.object2.id?
问题描述
我正在尝试使用 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”
解决方案
确保您的代码片段中的所有变量名称都是正确的
<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>
推荐阅读
- python - 迭代创建字典的麻烦
- r - 如何在 R 的单列中通过字符串标签对行值进行子集化?
- c++ - C++ SDL2 上的 Makefile
- php - 为什么此任务在 Windows 10 中并非每分钟都运行?
- javascript - chartjs & asp.net:无法读取未定义的属性“标签”
- jenkins - Jenkins 摘要显示插件的问题
- flutter - 如何让细胞的整个区域都感知到触摸?
- react-native - 对齐输入文本以从左侧开始,如占位符文本
- java - Java Spring-BOOT:HTTP处理程序旁边的主循环
- azure-iot-hub - Azure IoT 中心令牌格式和选项