javascript - Vue - 使用 v-for 两次来呈现表行和单元格?

标签 javascript vue.js

我想使用 Vue 来呈现一个包含行但将单元格作为组件的表格。

我做了a working example我希望看到的最终结果,并有一些代码与我认为我可以如何解决这个问题有关:

HTML

<div id="app">
  <table>
    <thead>
      <tr>
        <th>Row</th>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, rindex) in people">
        <td>{{ rindex }}</td>
        <cell v-for="(value, vindex, rindex) in row" :value="value" :vindex="vindex" :rindex="rindex"></cell>
      </tr>
    </tbody>
  </table>
  <template id="template-cell">
    <td>{{ value }}</td>
  </template>
</div>

JS

// Register component
Vue.component('cell', {
  template: '#template-cell',
  name: 'row-value',
  props: ['value', 'vindex', 'rindex']
  // In here I would like to access value, vindex and rindex
});
// Start application
new Vue({
  el: '#app',
  data: {
    people: [
      {id: 3, name: 'Bob', age: 27},
      {id: 4, name: 'Frank', age: 32},
      {id: 5, name: 'Joe', age: 38}
    ]
  }
});

这是因为,在 Vue 中 documentation on v-for他们展示了这个例子:

And another for the index:

<div v-for="(value, key, index) in object">
  {{ index }}. {{ key }} : {{ value }}
</div>

所以从逻辑上讲,我应该能够毫无问题地获取单元格组件中的行索引,但是this is not so因为它出现了一堆错误,表明这些值未定义。

如果有人能在这里指出我正确的方向,那么我将不胜感激,因为我对这个问题毫无想法,但真的很想了解如何正确实现。

(注意:我想要在组件中呈现单元格的原因是注册值的更改,see the answer 到我在这里问的另一个问题,如果你感兴趣的话)

最佳答案

您只需将cell 组件包含在template 元素中,这是因为HTML 中的表格需要only td inside tr。 ,当它看到 cell 时,它不会渲染它(参见 Angular 的类似问题 here )。但是模板可以在这里用作内容片段,在 vue 编译后,它会添加 tr 代替 HTML 中的单元格。

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

见工作笔here .

关于javascript - Vue - 使用 v-for 两次来呈现表行和单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153396/

相关文章:

javascript - 在 FireFox 中使用 javascript 解析日期

vue.js - 为什么在删除 vue 2 时数据会泄漏到同级组件实例中

javascript - 如何查看Vue组件中的多个属性?

Javascript props 分配没有 key?

javascript - 多种预定义样式或动态更改内联样式?

javascript - 如何让脚本在 Jade 中跨越多行?

unit-testing - 在 meteor 下用 Mocha/Chai 测试时 Vue $el 未定义

vue.js - 为什么 Vue3 路由器不传递带有参数的 Prop ?

javascript - Vue.js 全局事件总线

javascript - JS如何只查看表格中的H2标签