Vue - 使用v-two两次渲染表行和单元格?

Cra*_*der 3 javascript vue.js

我想使用Vue渲染一个包含行的表,但是将单元格作为一个组件.

我已经做了一个我希望看到的最终结果的例子,并且有一些代码与我认为我可以解决这个问题有关:

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>
Run Code Online (Sandbox Code Playgroud)

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}
    ]
  }
});
Run Code Online (Sandbox Code Playgroud)

这是因为,在v- vue 的Vue 文档中,他们展示了这个例子:

And another for the index:

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

所以从逻辑上思考,我应该能够在单元组件中获取行索引而不会出现太多问题,但事实并非如此,因为它会出现一堆错误,表明值未定义.

如果有人能指出我在这里正确的方向,那么我会非常感激它,因为我对这个问题缺乏想法,但我真的想了解如何正确实现这一点.

(注意:我想要在组件中渲染单元格的原因是注册值的更改,如果您感兴趣,请参阅我在这里询问的另一个问题的答案)

Sau*_*abh 9

你只需要将你的cell组件包含在一个template元素中,这是因为HTML中的表只需要tr中的td,当它看到时cell,它不会呈现它(在这里看到与Angular类似的问题).但是,模板可以在这里用作内容片段,在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>
Run Code Online (Sandbox Code Playgroud)

看到工作笔在这里.