使用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: ['Name', 'Age', 'Email'],
rows: [
{ Name: 'Alice', Age: 25, Email: 'alice@example.com' },
{ Name: 'Bob', Age: 30, Email: 'bob@example.com' },
],
};
},
};
</script>
动态数据绑定
从 API 获取数据并渲染表格。

<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.title }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
items: [],
};
},
async created() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
this.items = await response.json();
},
};
</script>
排序功能
通过计算属性实现表格数据的排序。
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">Name</th>
<th @click="sortBy('age')">Age</th>
</tr>
</thead>
<tbody>
<tr v-for="person in sortedPeople" :key="person.id">
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
people: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
],
sortKey: '',
sortOrder: 1,
};
},
computed: {
sortedPeople() {
return [...this.people].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>
使用第三方库
对于更复杂的表格需求,可以使用现成的 Vue 表格库,如 vue-good-table 或 ag-grid-vue。

安装 vue-good-table:
npm install vue-good-table
示例代码:
<template>
<vue-good-table
:columns="columns"
:rows="rows"
:sort-options="{
enabled: true,
}"
/>
</template>
<script>
import { VueGoodTable } from 'vue-good-table';
export default {
components: {
VueGoodTable,
},
data() {
return {
columns: [
{ label: 'Name', field: 'name' },
{ label: 'Age', field: 'age' },
],
rows: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
],
};
},
};
</script>
响应式样式
通过 CSS 为表格添加基础样式,使其适应不同屏幕尺寸。
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
cursor: pointer;
}
以上方法涵盖了从基础实现到高级功能的表格开发,可根据需求选择适合的方案。






