我尝试使用Vue框架填充HTML表中的行-数据如下所示:
TeamRows: [
{ team: 'One', times: ['1', '2', '3'] },
{ team: 'Two', times: ['4', '5', '6'] },
{ team: 'Three', times: ['7', '8', '9'] }
]我试着使用这个codepen,但是结果不好--这是我的:
<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一样多的列中跟随。希望有更多Vue知识的人能在这里帮助我。干杯。
发布于 2017-07-05 20:06:37
事实证明,原因是您使用的是in-DOM模板,而浏览器将未知的cell元素移动到v-for之上,而Vue不能再访问行值:https://vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats
没有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>
https://stackoverflow.com/questions/44924236
复制相似问题