vue实现表格内容
Vue实现表格内容的方法
使用原生HTML表格
通过Vue的数据绑定和循环指令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>
使用Element UI表格组件
Element UI提供了功能丰富的表格组件,支持排序、分页、筛选等高级功能。
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2023-01-01',
name: '王小虎',
address: '上海市普陀区'
}, {
date: '2023-01-02',
name: '李小狼',
address: '北京市海淀区'
}]
}
}
}
</script>
实现可编辑表格
通过结合v-model和自定义组件实现表格单元格编辑功能。
<template>
<table>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex">
<td v-for="(cell, colIndex) in row" :key="colIndex">
<input v-model="rows[rowIndex][colIndex]" />
</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
rows: [
['数据1', '数据2'],
['数据3', '数据4']
]
}
}
}
</script>
使用VxeTable高级表格
VxeTable提供了更强大的表格功能,包括虚拟滚动、树形表格、导出Excel等。
<template>
<vxe-table :data="tableData">
<vxe-column type="seq" title="序号" width="60"></vxe-column>
<vxe-column field="name" title="名称"></vxe-column>
<vxe-column field="role" title="角色"></vxe-column>
<vxe-column field="age" title="年龄"></vxe-column>
</vxe-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'test1', role: '前端', age: 26 },
{ id: 2, name: 'test2', role: '后端', age: 28 }
]
}
}
}
</script>
实现服务端分页
结合API请求实现服务端分页表格,适用于大数据量场景。

<template>
<el-table
:data="tableData"
@current-change="handleCurrentChange"
:total="total">
<!-- 列定义 -->
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
total: 0
}
},
methods: {
fetchData(page) {
// 调用API获取分页数据
api.getTableData(page).then(res => {
this.tableData = res.data
this.total = res.total
})
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData(val)
}
},
created() {
this.fetchData(1)
}
}
</script>






