vue实现表格输出
Vue 实现表格输出的方法
使用原生 HTML 表格
在 Vue 模板中可以直接使用 HTML 的 <table> 标签来创建表格,结合 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>
使用第三方表格组件
对于更复杂的表格需求,可以使用第三方库如 Element UI 或 Vuetify 提供的表格组件。

以 Element UI 为例:
<template>
<el-table :data="tableData">
<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 {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
实现分页功能
结合分页组件实现表格数据的分页显示。

<template>
<div>
<el-table :data="currentPageData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [...],
currentPage: 1,
pageSize: 10
}
},
computed: {
total() {
return this.tableData.length
},
currentPageData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.tableData.slice(start, end)
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
}
}
}
</script>
实现排序功能
通过添加排序方法实现表格数据的排序。
<template>
<el-table :data="sortedData" @sort-change="handleSortChange">
<el-table-column prop="name" label="Name" sortable></el-table-column>
<el-table-column prop="age" label="Age" sortable></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [...],
sortProp: '',
sortOrder: ''
}
},
computed: {
sortedData() {
if (!this.sortProp) return this.tableData
return [...this.tableData].sort((a, b) => {
let result = a[this.sortProp] > b[this.sortProp] ? 1 : -1
return this.sortOrder === 'descending' ? -result : result
})
}
},
methods: {
handleSortChange({ prop, order }) {
this.sortProp = prop
this.sortOrder = order
}
}
}
</script>
实现表格筛选
添加筛选功能允许用户按条件过滤表格数据。
<template>
<div>
<el-input v-model="filterText" placeholder="Filter"></el-input>
<el-table :data="filteredData">
<!-- 表格列定义 -->
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [...],
filterText: ''
}
},
computed: {
filteredData() {
if (!this.filterText) return this.tableData
return this.tableData.filter(item =>
item.name.toLowerCase().includes(this.filterText.toLowerCase())
)
}
}
}
</script>
这些方法涵盖了 Vue 中实现表格输出的基本功能,包括基础表格渲染、使用第三方组件库、分页、排序和筛选等功能。根据具体需求可以选择合适的实现方式。






