Vue table 在一个循环中 html

Vue table in one loop html

我有一个数组,里面有鞋子的尺码和店里的数量,结构如下:

array = {
    36=>1,   
    37=>0,
    38=>5,
    39=>2
}

在我的table键中这个table(这里是36、37 ...)是TH,值是TD。 我不能在一个循环中做到这一点。我这样试过:

<table class="table">
    <tr>
        <th v-for="(quantity, key) in productSizes" :key='key'>{{key}}</th>
    </tr>

    <tr>
    <td>Here should be quantity for each size<td>
    </tr>

</table>

是否可以一次完成?

结构如下(有一个输入,因为有人可以更改数量)。

我认为正确的做法是使用模板。我没有亲自测试代码,但这似乎是正确的方法。

Similar example found here

<tbody>
<template v-for="(quantity, key) in productSizes" :key='key'>
    <tr>
        <th>{{key}}</th>
    </tr>
    <tr>
        <td>{{key}}<td>
    </tr>
</template>
</tbody>

编辑

使用上面的示例使其与单个 v-for 循环一起工作(这次有时间对其进行测试)。

const productSizes = {
  36: 0,
  37: 2,
  38: 1,
  39: 3,
  40: 2,
  41: 0
}

new Vue({
  el: "#app",
  data:{
    productSizes
  }
})
<script src="https://unpkg.com/vue@2.4.2/dist/vue.js"></script>

<div id="app">
  <table>
    <tbody>
      <template v-for="(quantity, key) in productSizes">
          <tr>
              <th>{{key}}</th>
          </tr>
          <tr>
          <td><input v-model="productSizes[key]" type="text"><td>
          </tr>
      </template>
    </tbody>
  </table>
</div>

我想不出有一种方法可以在一个循环中执行此操作,我认为也不值得为此付出努力。只需对相同的数据结构进行第二次循环,您将始终获得匹配的列。

console.clear()

const shoeSizes = {
  36: 0,
  37: 2,
  38: 1,
  39: 3,
  40: 2,
  41: 0
}

new Vue({
  el: "#app",
  data:{
    shoeSizes
  }
})
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
  <table>
    <tr>
      <th v-for="quantity, key in shoeSizes">{{key}}</th>
    </tr>
    <tr>
      <td v-for="quantity, key in shoeSizes">
        <input type="text" v-model="shoeSizes[key]">
      </td>
    </tr>
  </table>
</div>

假设有 100 种鞋码,性能影响可以忽略不计。

编辑

好吧,我能想到一种在一个循环中渲染它的方法。使用渲染函数。

console.clear()

const shoeSizes = {
  36: 0,
  37: 2,
  38: 1,
  39: 3,
  40: 2,
  41: 0
}

new Vue({
  el: "#app",
  data:{
    shoeSizes
  },
  render(h){
    let headers = [], cells = []
    // build the headers and cells
    for (let key of Object.keys(this.shoeSizes)){
      // header is easy
      headers.push(h('th', key))
      
      // build props for the input to implement v-model
      let vmodel = {
        domProps: {
          value: this.shoeSizes[key]
        },
        on: {
          input: event => {
            this.$set(this.shoeSizes, key, event.target.value) 
            this.$emit('input', event.target.value)
          }
        }
      }
      // add the vell
      cells.push(h('td', [h('input', vmodel)]))      
    }
    // render the table with headers and cells in the 
    // right places
    return h('table', [h('tr', headers), h('tr', cells)])
  }
})
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app"></div>

此渲染函数在同一个循环中构建 headers 和单元格,然后在它们周围渲染 table。但我想你会同意这是不必要的复杂。