Vue CLI - Разбор вложенных данных в компоненте из локального JSON - PullRequest
1 голос
/ 02 апреля 2020

Я хочу отобразить следующий вид из JSON с компонентом Vue:

article inside a section

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

И для анализа этих данных я написал следующий компонент Vue:

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

Я определенно что-то упустил в этом коде. Я получаю только первые данные второго заголовка. Пожалуйста, предоставьте Vue CLI-решение вместо Vue. js, так как я новичок и еще не обладаю большими знаниями.

Ответы [ 2 ]

1 голос
/ 02 апреля 2020

Во-первых, всякий раз, когда у вас есть список данных в вашем JSON, используйте массив вместо объекта с пронумерованными индексами. Например:

const json = [
  {
    "title": "Title0",
    "content": [
      {
        "text": "few text here",
        "image": false
      }
    ]
  }
]
...

Я изменил имя jsonTitle на profiles, представляя, что это некоторые данные профиля. Это делает шаблон более понятным для изучения, поскольку у вас есть две петли. Каждый l oop имеет свой собственный индекс, используемый в качестве ключа. Вот как должен выглядеть ваш компонент:

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

Была также опечатка с imagepath вместо imagePath. Вот демо

0 голосов
/ 02 апреля 2020

Получены ли данные "JSON" от серверной части или вы их формируете. Если вы формируете JSON, вместо предоставления объектов внутри объектов создайте массив объектов, как показано ниже.

[
 {
    "title": "Title0",
    "content": [
      {
        "text": "few text here",
        "image": false
      }
    ]
  },
 {
    "title": "Title1",
    "content": [
      {
        "text": "few text here",
        "image": false
      },
      {
        "text": "few text here",
        "image": true,
        "imagePath": "../../Assets/images.sample.png"
      }
    ]
  }
]
...