【问题标题】:How do I loop through an array in Vue half the amount of times as there are items?如何在 Vue 中循环遍历数组的次数是有项目的一半?
【发布时间】:2018-12-15 10:44:09
【问题描述】:

我有一个数据数组:

[
  {
    type: select, 
    options: [foo, bar], 
    label: foo, 
    required: true
  }, 
  {
    type: text, 
    options: [],
    label: bar, 
    required: false
  }, 
  {
    type: checkbox, 
    options: [], 
    label: baz, 
    required: true
  }
]

还有一个 Vue 模板:

<b-row>
  <b-col>
    <label :for="{{label}}">{{ label }}<span class="required" v-if="required"/></label>
    {{ checks type and injects proper form element here }}
  </b-col>
</b-row>

我试图找出如何最好地遍历每个对象,并将每个对象放入自己的&lt;b-col&gt;,每行只有两列,使其看起来类似于以下结构:强>

<b-row>
  <b-col>
    <label for="size">foo<span class="required" v-if="required"/></label>
    <b-form-select id="size">
      <options>foo</options>
      <options>bar</options>
    </b-form-select>
  </b-col>
  <b-col>
    <label for="size">bar<span class="required" v-if="required"/></label>
    <b-form-text id="size"/>
  </b-col>
</b-row>
<b-row>
  <b-col>
    <label for="size">baz<span class="required" v-if="required"/></label>
    <b-form-select id="size"/>
  </b-col>
    <label for="size">barbaz<span class="required" v-if="required"/></label>
    <b-form-select id="size"/>
  </b-col>
</b-row>
...etc.

我正在努力寻找以类似 vue 的方式干净利落地完成此任务的最佳方法。

【问题讨论】:

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


    【解决方案1】:

    您可以遍历数组,将每个元素放在 b-col 中,并将每列的宽度指定为 50%,如下所示:

    <b-row>
        <b-col v-for="item in array" sm="6">
            ...do something with item
        </b-col>
    </b-row>
    

    sm="6" 告诉引导程序使用等于 6 列的空间量(即 50%) 我不确定 vue-bootstrap,但引导文档指出:

    如果在一行中放置超过 12 列,则每组 额外的列将作为一个单元换行

    https://getbootstrap.com/docs/4.1/layout/grid/#column-wrapping

    【讨论】:

    • 谢谢@puelo,这确实解决了我的问题。我将其标记为正确,我很欣赏迅速的答复,但我很好奇是否有人也对我原来的问题有答案。我总是对学习完成事情的新方法很感兴趣。
    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 2013-11-15
    • 2019-09-04
    • 2020-06-08
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多