vue实现简单表格
使用 Vue 实现简单表格
Vue 提供了多种方式实现表格功能,以下是基于 Vue 3 的两种常见方法:
基础表格实现
通过 v-for 指令循环渲染表格数据:
<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="(value, key) in row" :key="key">
{{ value }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
rows: [
{ 姓名: '张三', 年龄: 25, 职业: '工程师' },
{ 姓名: '李四', 年龄: 30, 职业: '设计师' }
]
}
}
}
</script>
使用组件化表格
创建可复用的表格组件:
<!-- TableComponent.vue -->
<template>
<table>
<slot name="header"></slot>
<slot name="body"></slot>
</table>
</template>
<!-- 使用组件 -->
<template>
<TableComponent>
<template #header>
<thead>
<tr>
<th v-for="header in headers" :key="header">
{{ header }}
</th>
</tr>
</thead>
</template>
<template #body>
<tbody>
<tr v-for="(row, index) in rows" :key="index">
<td v-for="(value, key) in row" :key="key">
{{ value }}
</td>
</tr>
</tbody>
</template>
</TableComponent>
</template>
添加交互功能
实现排序和筛选功能示例:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers"
:key="header.key"
@click="sortBy(header.key)">
{{ header.text }}
<span v-if="sortKey === header.key">
{{ sortOrder > 0 ? '↑' : '↓' }}
</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="row in sortedRows" :key="row.id">
<td v-for="header in headers" :key="header.key">
{{ row[header.key] }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
sortKey: '',
sortOrder: 1,
headers: [
{ text: '姓名', key: 'name' },
{ text: '年龄', key: 'age' }
],
rows: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
]
}
},
computed: {
sortedRows() {
return [...this.rows].sort((a, b) => {
return a[this.sortKey] > b[this.sortKey] ? this.sortOrder : -this.sortOrder
})
}
},
methods: {
sortBy(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
样式优化
为表格添加基础样式:
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
cursor: pointer;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
以上示例展示了 Vue 实现表格的核心方法,可以根据实际需求扩展分页、编辑等功能。







