【问题标题】:How to loop through 2-d array to display data on page?如何循环遍历二维数组以在页面上显示数据?
【发布时间】:2021-11-13 08:15:10
【问题描述】:

这个 API 返回一个像这样的二维数组

我想使用这些值来迭代并像这样显示在我的页面上

我查看了vue 文档,但列表渲染不起作用。有什么办法可以用v-for 或任何其他方法做到这一点?

【问题讨论】:

  • 您能否展示一下您的code 以及您到目前为止所做的尝试。

标签: arrays vue.js multidimensional-array vuejs3 v-for


【解决方案1】:

如果我理解正确,请尝试如下 sn-p :

new Vue({
  el: '#demo',
  data(){
    return {
      sections: [
        [699962583, 'Sep 17'],
        [12665354, 'Sep 17'],
        [739845240, 'Sep 17']
      ]
    }
  },
  computed: {
    currentPrize(){
      // put logic to get current prize
      return 6543210
    }
  }
})
ul {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 300px;
}
li, .heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
h1, h3, h5 {
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <ul>
    <h1>Past Prizes</h1>
    <div class="heading">
      <h5>Current prizes</h5><h3>$ {{ currentPrize }}</h3>
    </div>
    <li v-for="(section, index) in sections" :key="index">
      <h5>{{ section[1] }}</h5><span>$ {{ section[0] }}</span>
    </li>
  </ul>
</div>

【讨论】:

    【解决方案2】:

    有两种方式:

    一种是将数组转换为对象数组并迭代为v-for和value.date和value.price in v-for="value in array"

    [{
     date: 'dd//mm/yy',
     price: 3242,
    }]
    

    其他是像这样使用数组,以数组中的元素应该]恒定的方式编写,其中 value[0] 是您的价格 ad value[1] 是您的日期。

      <div v-for="value in array">
        {{value[0]}}     {{value[1]}}
      </div>
    

    【讨论】:

      【解决方案3】:

      您可以简单地通过循环并破坏v-for 指令中的子数组来实现。请参考以下示例:

      Vue.config.productionTip = false
      Vue.config.devtools = false
      
      new Vue({
        el: '#app',
        data() {
          return {
            sections: [
              [699962583, 'Sep 17'],
              [12665354, 'Sep 17'],
              [739845240, 'Sep 17']
            ]
          }
        },
        computed: {
          currentPrize() {
            return this.sections.reduce(function(prev, current){ return prev += current[0]; }, 0);
          }
        }
      })
      ul {
        list-style-type: none;
        width: 400px;
      }
      
      li {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
      <div id="app">
        <h1>Past Prizes</h1>
        <ul>
          <li><span>Current prizes</span><span>${{ currentPrize }}</span></li>
          <li v-for="([prize, date], index) in sections" :key="index">
            <span>{{ date }}</span> <span>${{ prize }}</span>
          </li>
        </ul>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-22
        • 1970-01-01
        • 2013-12-27
        • 1970-01-01
        • 2016-07-02
        • 2019-02-04
        • 2018-03-09
        • 1970-01-01
        相关资源
        最近更新 更多