vue循环实现表格
Vue 循环实现表格的方法
在 Vue 中,可以通过 v-for 指令实现表格的循环渲染。以下是几种常见的实现方式:
基础表格循环
<template>
<table>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 },
{ name: '王五', age: 28 }
]
}
}
}
</script>
动态表头与数据
<template>
<table>
<thead>
<tr>
<th v-for="(header, index) in tableHeaders" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableHeaders: ['姓名', '年龄', '职业'],
tableData: [
['张三', 25, '工程师'],
['李四', 30, '设计师'],
['王五', 28, '产品经理']
]
}
}
}
</script>
嵌套对象数据
<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>地址</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.address.city }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
users: [
{ id: 1, name: '张三', address: { city: '北京' } },
{ id: 2, name: '李四', address: { city: '上海' } }
]
}
}
}
</script>
带条件的循环
<template>
<table>
<tr v-for="item in filteredItems" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '项目A', value: 100, active: true },
{ id: 2, name: '项目B', value: 200, active: false }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.active)
}
}
}
</script>
表格分页实现
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage >= pageCount">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '项目1', value: 10 },
{ id: 2, name: '项目2', value: 20 },
// ...更多数据
],
currentPage: 1,
itemsPerPage: 5
}
},
computed: {
pageCount() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.pageCount) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
注意事项
- 始终为
v-for提供:key属性,使用唯一标识符而非数组索引 - 复杂表格建议拆分为多个组件,提高可维护性
- 大数据量表格考虑使用虚拟滚动技术优化性能
- 表格样式可通过 CSS 或 UI 框架(如 Element UI、Ant Design Vue)增强
以上方法涵盖了 Vue 中实现表格循环的基本场景,可根据实际需求组合使用或进一步扩展。







