vue 实现页面 表格
Vue 实现页面表格的方法
在 Vue 中实现表格可以通过多种方式完成,以下是几种常见的方法:
使用原生 HTML 表格
Vue 支持直接使用 HTML 的 <table> 标签,通过 v-for 动态渲染表格数据。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>职业</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.job }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25, job: '工程师' },
{ name: '李四', age: 30, job: '设计师' }
]
}
}
}
</script>
使用第三方表格组件库
许多 Vue 的 UI 框架提供了功能丰富的表格组件,例如 Element UI、Ant Design Vue 或 Vuetify。

以 Element UI 为例:
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="age" label="年龄" width="180"></el-table-column>
<el-table-column prop="job" label="职业"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25, job: '工程师' },
{ name: '李四', age: 30, job: '设计师' }
]
}
}
}
</script>
自定义表格组件
如果需要更灵活的表格功能,可以创建自定义的表格组件。

<template>
<div class="custom-table">
<div class="header">
<div v-for="col in columns" :key="col.prop" class="header-cell">
{{ col.label }}
</div>
</div>
<div class="body">
<div v-for="(row, index) in data" :key="index" class="row">
<div v-for="col in columns" :key="col.prop" class="cell">
{{ row[col.prop] }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
columns: {
type: Array,
required: true
},
data: {
type: Array,
required: true
}
}
}
</script>
实现表格的高级功能
对于更复杂的需求,如排序、分页、筛选等,可以结合计算属性和方法来实现。
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">姓名</th>
<th @click="sortBy('age')">年龄</th>
<th>职业</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.job }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25, job: '工程师' },
{ id: 2, name: '李四', age: 30, job: '设计师' }
],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedData() {
if (!this.sortKey) return this.tableData
return [...this.tableData].sort((a, b) => {
return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortOrder
})
}
},
methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortOrder *= -1
} else {
this.sortKey = key
this.sortOrder = 1
}
}
}
}
</script>
响应式表格数据更新
当表格数据需要从 API 获取时,可以使用异步方法更新数据。
<template>
<table>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: []
}
},
async created() {
try {
const response = await fetch('https://api.example.com/data')
this.tableData = await response.json()
} catch (error) {
console.error('获取数据失败:', error)
}
}
}
</script>
以上方法涵盖了从简单到复杂的 Vue 表格实现方式,可以根据具体需求选择适合的方案。






