实现vue table
Vue Table 实现方法
基础表格实现
使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.id">
<td v-for="cell in row" :key="cell">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['ID', 'Name', 'Age'],
rows: [
{ id: 1, Name: 'Alice', Age: 25 },
{ id: 2, Name: 'Bob', Age: 30 }
]
}
}
}
</script>
使用组件库
对于更复杂的需求,可以使用现成的 Vue 表格组件库如 Element UI、Vuetify 或 Ant Design Vue。这些库提供了排序、分页、筛选等高级功能。
以 Element UI 为例:
<template>
<el-table :data="tableData">
<el-table-column prop="date" label="Date" width="180"></el-table-column>
<el-table-column prop="name" label="Name" width="180"></el-table-column>
<el-table-column prop="address" label="Address"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-02',
name: 'John',
address: 'New York'
}]
}
}
}
</script>
自定义功能
需要实现特定功能时,可以扩展基础表格组件。例如添加行选择功能:
<template>
<table>
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.id">
<td><input type="checkbox" v-model="selectedRows" :value="row.id"></td>
<td v-for="cell in row" :key="cell">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
selectedRows: [],
selectAll: false,
// 其他数据...
}
},
watch: {
selectAll(val) {
this.selectedRows = val ? this.rows.map(row => row.id) : []
}
}
}
</script>
性能优化
处理大量数据时,应考虑虚拟滚动或分页加载。第三方库如 vue-virtual-scroller 可以高效渲染大型表格:

<template>
<RecycleScroller
class="scroller"
:items="rows"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="row">
<div v-for="cell in item" :key="cell">{{ cell }}</div>
</div>
</RecycleScroller>
</template>






