如何使用 Vuejs 和 Axios 读取深度 JSON 数据



如何读取嵌套在文件深处的深度JSON数据?我尝试了不同的方法,但似乎无法使其工作。

<template>
<div>
<div v-for="edu in info" :key="edu">
<div>{{ edu.section.title }}</div> // this is what im trying to get to work
</div>
<div class="card container">
{{ info }}
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
info: null
}
},
mounted() {
axios
.get('./calculus.json') // Data Below
.then(response => (this.info = response.data.edu))
.catch(error => console.log(error))
}
}
</script>

我的 JSON 看起来像这样:

{
"edu": {
"1": {
"title": "Title One",
"subtitle": "Subtitle One",
"description": "Description One",
"section": {
"1": {
"title": "Section One Title",
"content": "Section One Content"
}
}
},
"2": {
"title": "Title Two",
"subtitle": "Subtitle Two",
"description": "Description Two",
"section": {
"1": {
"title": "Section One Title",
"content": "Section One Content"
}
}
}
}
}

如何使用 vue-for 并获取部分内的数据以使其显示在标题下?例如:标题、章节>标题、章节>副标题等。

鉴于每个section也是一个具有奇怪数字键的对象,您可以像info一样迭代它们。

我还建议您在:key绑定中使用可识别的值而不是整个edu对象。

<div v-for="(edu, eduId) in info" :key="eduId">
<div v-for="(section, sectionId) in edu.section" :key="sectionId">
{{ section.title }}
</div>
</div>

如果可能的话,我会更改 JSON 数据的格式以使用实际数组而不是带有数字键的对象。

深入浏览对象的一种方法是在对象(和子项(条目上累积 v-for。

即:

<div v-for="([category, books], catkey) in Object.entries(info)" :key="`category-${catkey}`">
<div>{{ category }} :</div>
<div v-for="([num, book], numkey) in Object.entries(books)" :key=`book-${catkey}-${numkey}`>
<div v-for="([field, value], valkey) in Object.entries(book)" :key=`field-${catkey}-${numkey}-${valkey}`>
{{ field }} : {{ value }}
</div>
</div>
</div>

如果发现它过于冗长,可以尝试将计算数据平展为具有以下结构:

[
{
"category": "edu",
"id": "1",
"title": "Title One",
"subtitle": "Subtitle One",
"description": "Description One",
"section": {
"1": {
"title": "Section One Title",
"content": "Section One Content"
}
}
}
]

最新更新