首页 > 解决方案 > 可以像这样访问 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”

标签: javascripthtmljsonvue.jsvuejs3

解决方案


确保您的代码片段中的所有变量名称都是正确的

<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>

推荐阅读