【问题标题】:How to display nested json array with v-for index loop如何使用 v-for 索引循环显示嵌套的 json 数组
【发布时间】:2021-06-25 04:18:21
【问题描述】:

我有以下结构的 JSON 数组

    items: [
     {
      ID: 11,
      UserID: "test.com",
      UserRole: "user",
      timeStamp: "2021-03-23T15:54:02.125578",
      dialogs: [
        {
          "Bot": "Why is data missing?",
          "test.com": "not available",
          "Bot": "please enter ID",
          "test.com": "1234"

        }
      ]
    }
  ]

我必须将对话框内的元素显示为列表。我正在使用 v-for,但对话框显示为带逗号的数组。我如何用索引显示这个?以下是我正在使用的 v-for 循环

    <ul v-for="item  in items" :key="item">
        <li v-for="(dialog, index) in dialogs" :key="index">{{key}}: {{dialogs}}</li>
    </ul>

【问题讨论】:

  • 在该 li 内的 span 中使用另一个 v-for

标签: javascript arrays json vue.js v-for


【解决方案1】:

需要进行 2 处更改。

  • 在您的 dialogs 中,您有重复的键,因此需要将它们分成两个不同的对象。
  • 在您的 HTML 部分中,您需要循环为 items.dialogs

这是完整的代码。

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    items: [
     {
      ID: 11,
      UserID: "test.com",
      UserRole: "user",
      timeStamp: "2021-03-23T15:54:02.125578",
      dialogs: [
        {
          "Bot": "Why is data missing?",
          "test.com": "not available",
          },
          
          {"Bot": "please enter ID",
          "test.com": "1234"
        }
      ]
    }
  ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
 <ul v-for="(item, index) in items" :key="item">
     <li v-for = "(data, index) in item.dialogs"> 
 {{data}}  {{index}}</li>
    </ul>
</div>

【讨论】:

    【解决方案2】:
     <ul v-for="item  in items" :key="item">
          <li v-for="(dialog, index) in item.dialogs" :key="index">{{index}}: {{dialog}}</li>
      </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2019-12-01
      相关资源
      最近更新 更多