vue2.0 实现table
Vue 2.0 实现表格(Table)的方法
基础表格实现
使用原生HTML表格标签结合Vue的数据绑定,可以快速实现动态表格渲染。通过v-for指令遍历数据数组生成表格行。
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td v-for="(value, key) in item" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
tableData: [
{ 姓名: '张三', 年龄: 25, 职业: '工程师' },
{ 姓名: '李四', 年龄: 30, 职业: '设计师' }
]
}
}
}
</script>
使用第三方组件库
对于复杂需求,推荐使用成熟的UI组件库:
-
Element UI表格组件:
<el-table :data="tableData"> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> </el-table> -
Vuetify数据表格:
<v-data-table :headers="headers" :items="items"></v-data-table>
自定义高级功能
需要实现排序、分页等功能时,可扩展基础表格:
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">姓名</th>
<th @click="sortBy('age')">年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedData() {
return [...this.tableData].sort((a, b) => {
return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortOrder
})
}
},
methods: {
sortBy(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
性能优化建议
对于大数据量表格(超过1000行),建议采用虚拟滚动技术。可使用vue-virtual-scroller等库:
<template>
<RecycleScroller
class="table"
:items="tableData"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="row">
<div class="cell">{{ item.name }}</div>
<div class="cell">{{ item.age }}</div>
</div>
</RecycleScroller>
</template>
响应式设计技巧
通过CSS媒体查询使表格在不同设备上表现良好:
@media screen and (max-width: 600px) {
table {
display: block;
overflow-x: auto;
}
}
注意事项
- 始终为
v-for设置唯一的:key - 复杂表格建议拆分为子组件
- 大数据量避免直接使用
v-for渲染所有行 - 考虑添加加载状态和空数据提示







