I want to render the following view from JSON with a Vue component:
JSON:
{
"0": {
"title": "Title0",
"content": {
"0": {
"text": "few text here",
"image": false
}
}
},
"1": {
"title": "Title1",
"content": {
"0": {
"text": "few text here",
"image": false
},
"1": {
"text": "few text here",
"image": true,
"imagePath": "../../Assets/images.sample.png"
}
}
}
}
And to parse that data I have written the following Vue component:
<template>
<div>
<section v-for="(data, index) in jsonTitle" :key="index">
<h5>{{data.title}}</h5>
<article v-for="(data, index) in jsonTitle" :key="index">
<h6>{{data.content[0].text}}</h6>
<img v-if="data.content[0].image === true" v-bind:src="data.imagepath" alt="">
</article>
</section>
</div>
</template>
<script>
import json from "@/components/json/english.json";
export default {
name: "databox",
data() {
return {
jsonTitle: json
};
}
};
</script>
I am definitely missing something in this code. I only get the 1st data of the second title. Please provide a Vue CLI solution rather than Vue.js, as I am new and don't possess much knowledge yet.
First, any time you have a list of data in your JSON, use an array instead of an object with numbered indexes. For example:
const json = [
{
"title": "Title0",
"content": [
{
"text": "few text here",
"image": false
}
]
}
]
...
I changed the name jsonTitle
to profiles
, imagining that this is some profile data. It makes the template clearer to study, since you have two loops. Each loop has its own index used as a key. Here is how your component should look:
<template>
<div>
<section v-for="(profile, indexProfile) in profiles" :key="indexProfile">
<h5>{{ profile.title }}</h5>
<article v-for="(content, indexContent) in profile.content" :key="indexContent">
<h6>{{ content.text }}</h6>
<img v-if="content.image === true" :src="content.imagePath" alt="">
</article>
</section>
</div>
</template>
<script>
import json from "@/components/json/english.json";
export default {
name: "databox",
data() {
return {
profiles: json
};
}
};
</script>
There was also a typo with imagepath
instead of imagePath
. Here is a demo
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加