javascript - 在 Vue 中将 v-for 与嵌套对象一起使用

标签 javascript vue.js vuejs2

我有这种形式的数据:

itemlist : {
  "dates": [
    "2019-03-15", 
    "2019-04-01", 
    "2019-05-15"
  ], 
  "id": [
    "arn21", 
    "3sa4a", 
    "wqa99"
  ], 
  "price": [
    22, 
    10, 
    31
  ]
}

我想在我创建的组件中使用 v-for,该组件循环遍历该对象,将这 3 个嵌套数组中的每个索引视为一个观察。因此,dates[0]id[0]price[0] 对应于同一商品,dates[1] id[1] Price [1] 是第二位,依此类推。

所以换句话说,我认为我需要将其转换为,但不确定:

0 : {
dates: "2019-03-15", 
id: "arn21", 
price: 22,}
1:{
dates: "2019-04-01", 
id: "3sa4a", 
price: 10}
}
2:...

这就是我将数据传递给组件的方式:

<tempc v-for="i in itemlist" :key="i.id" :price="i.price" :dates="i.dates"></temp>

但这不适用于原始数据

最佳答案

您可以为此创建一个计算属性:

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      itemlist: {
        "dates": [
          "2019-03-15",
          "2019-04-01",
          "2019-05-15"
        ],
        "id": [
          "arn21",
          "3sa4a",
          "wqa99"
        ],
        "price": [
          22,
          10,
          31
        ]
      }
    };
  },
  computed: {
    // Note: here I assume these arrays will always have the same length
    mergedList() {
      return this.itemlist.dates.map((dates, i) => {
        return {
          dates,
          id: this.itemlist.id[i],
          price: this.itemlist.price[i]
        };
      });
    }
  }
});

var vm = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <ul>
    <li v-for="i in mergedList" :key="i.id" :price="i.price" :dates="i.dates">
      {{i.id}} - ${{i.price}} ({{i.dates}})
    </li>
  </ul>
</template>

关于javascript - 在 Vue 中将 v-for 与嵌套对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60252900/

相关文章:

javascript - 尽管在我的 Controller 中使用了await,为什么我还是收到Promise Pending?

javascript - JS 流 : What is the most clean and concise way to define an enum that is also treated like a type

vue.js - VueJS 扩展方法和数据

javascript - 替换后,跳过字符串的该部分 - Regex Javascript

JavaScript + MEAN 堆栈 : How to properly find "_id" field (not "id") in array?

javascript - 高效渲染大量 Redux 表单字段?

vue.js - 子级和父级涟漪触发

laravel - 当索引未知时更新特定数组条目

javascript - 如何重新运行 Vue.js ApolloClient 中间件?

vue.js - VueX - 在与 Action 不同的模块中调度 Action