vue 实现简单表格
以下是在 Vue 中实现简单表格的几种方法:
使用原生表格标签
通过 Vue 的数据绑定功能渲染表格数据:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="index">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
rows: [
['张三', 25, '工程师'],
['李四', 30, '设计师']
]
}
}
}
</script>
使用组件化方式
将表格拆分为可复用的组件:

<template>
<my-table :headers="headers" :rows="rows"></my-table>
</template>
<script>
import MyTable from './MyTable.vue'
export default {
components: { MyTable },
data() {
return {
headers: ['姓名', '年龄'],
rows: [
{ name: '王五', age: 28 },
{ name: '赵六', age: 35 }
]
}
}
}
</script>
添加交互功能
实现排序和筛选等常见表格功能:
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">姓名</th>
<th @click="sortBy('age')">年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedItems" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedItems() {
return [...this.items].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>
使用第三方库
对于更复杂的需求,可以考虑使用专门的表格组件库:

-
Element UI 的表格组件:
<template> <el-table :data="tableData"> <el-table-column prop="date" label="日期"></el-table-column> <el-table-column prop="name" label="姓名"></el-table-column> </el-table> </template> -
Vuetify 的数据表格:
<template> <v-data-table :headers="headers" :items="items"></v-data-table> </template>
这些方法涵盖了从基础到进阶的表格实现方式,可以根据项目需求选择合适的方案。对于简单表格,原生实现足够;对于复杂需求,推荐使用成熟的UI库。






