vue循环实现表格
vue循环实现表格
在Vue中,可以通过v-for指令实现表格数据的动态渲染。以下是几种常见场景的实现方法:
基础表格循环
使用v-for遍历数组数据生成表格行:
<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
动态表头循环
表头和表体数据同时循环:
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td v-for="col in columns" :key="col.key">{{ item[col.key] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
columns: [
{ key: 'id', title: 'ID' },
{ key: 'name', title: 'Name' }
],
tableData: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
}
}
}
</script>
嵌套数据循环
处理嵌套对象或数组:
<template>
<table>
<tr v-for="user in users" :key="user.id">
<td>{{ user.name }}</td>
<td>
<table>
<tr v-for="order in user.orders" :key="order.id">
<td>{{ order.product }}</td>
<td>{{ order.price }}</td>
</tr>
</table>
</td>
</tr>
</table>
</template>
带索引的循环
需要显示行号时使用索引:

<tr v-for="(item, index) in tableData" :key="item.id">
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
</tr>
性能优化建议
- 始终为
v-for提供唯一的:key属性 - 大数据量时考虑虚拟滚动方案
- 复杂表格可使用专用组件库如
Element UI的el-table
以上方法可根据实际需求组合使用,Vue的响应式特性会在数据变化时自动更新表格渲染。






