使用Vue使用包含数组的对象填充HTML表行

时间:2017-07-05 10:52:33

标签: data-binding html-table vue.js

我尝试使用Vue框架填充HTML表格中的行 - 数据如下所示:

TeamRows: [
            { team: 'One', times: ['1', '2', '3'] },
            { team: 'Two', times: ['4', '5', '6'] },
            { team: 'Three', times: ['7', '8', '9'] }
          ]

我已尝试关注此codepen,但效果不佳 - 这是我的HTML:

<tbody>
   <tr v-for="(row, rindex) in teamRows">
      <td>{{rindex}}</td>
         <template>
            <cell v-for="(value, vindex) in row" :value="value" :vindex="vindex" :rindex="rindex"></cell>
         </template>
   </tr>
</tbody>
</table>
<template id="template-cell">
   <td>{{ value }}</td>
</template>

这是Vue组件:

Vue.component('cell', {
    template: '#template-cell',
    name: 'row-value',
    props: ['value', 'vindex', 'rindex']
});

我希望team连续排在第一列,times跟随times列的数量与for一样多。希望有更多Vue知识的人能够帮助我。欢呼声。

1 个答案:

答案 0 :(得分:2)

原因是你正在使用in-DOM模板,浏览器将cell元素移到v-for之上,而Vue无法再访问行值:https://vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats < / p>

没有cell组件的解决方案,只有内联单元格元素,工作正常。此外,表格模板中不需要template包装器:

new Vue({
  el: '#app',
  data: {
    teamRows: [
      { team: 'One', times: ['1', '2', '3'] },
      { team: 'Two', times: ['4', '5', '6'] },
      { team: 'Three', times: ['7', '8', '9'] }
    ]
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <table>
    <tbody>
     <tr v-for="row in teamRows" :key="row.team">
       <td>{{ row.team }}</td>
       <td v-for="time in row.times">{{ time }}</td>
     </tr>
    </tbody>
  </table>
</div>

此外,作为讨论的结果,如果您将表包装到另一个组件中,您仍然可以使用组件,这样浏览器就不会干扰,Vue有机会正确呈现所有内容:

new Vue({
  el: '#app',
  data: {
    teamRows: [
      { team: 'One', times: ['1', '2', '3'] },
      { team: 'Two', times: ['4', '5', '6'] },
      { team: 'Three', times: ['7', '8', '9'] }
    ]
  }, 
  components: {
    'mytable': {
      template: `<table>
    <tbody>
     <tr v-for="row in rows" :key="row.team">
       <td>{{ row.team }}</td>
       <cell v-for="time in row.times" :value="time" :key="time"></cell>
     </tr>
    </tbody>
  </table>`,
      props: ['rows'],
      components: {
      	'cell': {
          template: `<td>{{ value }}</td>`,
      	  props: ['value'],
        }
      }
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <mytable :rows="teamRows"></mytable>
</div>