Vue如何正确遍历列表?

时间:2018-01-24 16:00:36

标签: javascript html vue.js vuejs2

我只是编写了vue简单代码,但无法遵循HTML效果。遍历渲染后有点不对劲。如果礼品对象为否,例如商品对象有两个数据goods_b1 + goods_b2。但我想遵循HTML效果。转到HTML still。然后转到vue loops

我想要这个效果:

enter image description here

看看javascript:

var app = new Vue({
  el: "#app",
  data: {
    list: [{
      id: 1,
      name: 'A',
      goods: [{
        name: "goods_a1"
      }],
      gift: [{
        name: "gift_a1",
      }]
    }, {
      id: 2,
      name: 'B',
      gift: [],
      goods: [{
        name: "goods_b1"
      }, {
        name: "goods_b2"
      }],
    }, {
      id: 3,
      name: 'C',
      goods: [{
        name: "goods_c1"
      }, {
        name: "goods_c2"
      }, {
        name: "goods_c3"
      }],
      gift: [{
        name: "gift_c1",
      }]
    }]
  }
})

HTML:

<div id="app">
  <div class="mui-row" v-for="item in list">
    <div class="span-title-main">
      <span class="span-title">{{item.name}}</span>
    </div>
    <br>
    <ul>

      <li>
        <div class="mui-col" v-for="items in item.goods">
          <span class="span-name">{{items.name}}</span>
        </div>
        <div class="addspan">+</div>
        <div class="mui-col" v-for="itemss in item.gift">
          <span class="span-name">{{itemss.name}}</span>
        </div>
        <div class="addspan">+</div>
      </li>
    </ul>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

看起来唯一的区别是您希望在每个+之后显示item.goods按钮,而不是在循环之后只显示一个。{/ p>

所以把它放在循环中:

    <template v-for="items in item.goods"><!-- using "template" to avoid modifying your html structure; you could of course use any tag -->
      <div class="mui-col">
        <span class="span-name">{{items.name}}</span>
      </div>
      <div class="addspan">+</div>
    </template>
    <div class="mui-col" v-for="items in item.gift">
      <span class="span-name">{{items.name}}</span>
    </div>
    <!-- your image doesn't show a + button after gifts, so I've omitted it here -->

答案 1 :(得分:0)

你是否要求(+)在你的商品和礼物的循环中?

<div id="app">
  <div class="mui-row" v-for="item in list">
    <div class="span-title-main">
      <span class="span-title">{{item.name}}</span>
    </div>
    <br>
    <ul>

      <li>
        <div class="mui-col" v-for="items in item.goods">
          <span class="span-name">{{items.name}}</span>
          <div class="addspan">+</div>
        </div>

        <div class="mui-col" v-for="itemss in item.gift">
          <span class="span-name">{{itemss.name}}</span>

        </div>

      </li>
    </ul>
  </div>
</div>

编辑:按照OP的要求删除礼物循环的(+)。

注意:如果OP要求在商品和礼品之间使用元素样式。我建议使用带有:last的css display:none选择器来产生这种效果。