vue实现tablegrid
Vue 实现 TableGrid
在 Vue 中实现一个表格网格(TableGrid)可以通过多种方式完成,以下是几种常见的方法:
使用原生 HTML 表格
通过 Vue 的模板语法直接渲染 HTML 表格,结合 v-for 动态生成行和列。
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data" :key="row.id">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['ID', 'Name', 'Age'],
data: [
{ 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="data">
<el-table-column prop="id" label="ID"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
data: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
自定义 TableGrid 组件
如果需要更灵活的功能,可以封装一个自定义的 TableGrid 组件。
<template>
<div class="table-grid">
<div class="header">
<div v-for="header in headers" :key="header" class="header-cell">{{ header }}</div>
</div>
<div class="body">
<div v-for="row in data" :key="row.id" class="row">
<div v-for="(value, key) in row" :key="key" class="cell">{{ value }}</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
headers: {
type: Array,
required: true
},
data: {
type: Array,
required: true
}
}
}
</script>
<style>
.table-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.header, .row {
display: contents;
}
.header-cell, .cell {
padding: 8px;
border: 1px solid #ddd;
}
</style>
动态列和排序
为表格添加动态列和排序功能:

<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header" @click="sortBy(header)">
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="row in sortedData" :key="row.id">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['ID', 'Name', 'Age'],
data: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedData() {
if (!this.sortKey) return this.data
return [...this.data].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>
以上方法可以根据需求选择适合的实现方式。原生表格适合简单需求,第三方组件库适合快速开发,自定义组件则提供了最大的灵活性。






