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 rows" :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'],
rows: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
使用第三方表格组件库
对于更复杂的需求,可以使用专门的 Vue 表格组件库如 Element UI 的 el-table 或 Vuetify 的 v-data-table。

<template>
<el-table :data="tableData">
<el-table-column prop="date" label="Date"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="address" label="Address"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ date: '2023-01-01', name: 'Alice', address: 'New York' },
{ date: '2023-01-02', name: 'Bob', address: 'London' }
]
}
}
}
</script>
实现可编辑表格
通过添加 v-model 绑定和 @input 事件可以实现单元格编辑功能。

<template>
<table>
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex">
<td v-for="(cell, colIndex) in row" :key="colIndex">
<input v-model="rows[rowIndex][colIndex]" @input="handleEdit(rowIndex, colIndex)">
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
rows: [
['Alice', '25'],
['Bob', '30']
]
}
},
methods: {
handleEdit(rowIndex, colIndex) {
console.log(`Edited row ${rowIndex}, column ${colIndex}`)
}
}
}
</script>
实现虚拟滚动表格
对于大数据量的表格,可以使用虚拟滚动技术优化性能。可以使用 vue-virtual-scroller 等库。
<template>
<RecycleScroller
class="table"
:items="rows"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="row">
<div class="cell">{{ item.id }}</div>
<div class="cell">{{ item.name }}</div>
<div class="cell">{{ item.age }}</div>
</div>
</RecycleScroller>
</template>
<style>
.table {
height: 500px;
}
.row {
display: flex;
}
.cell {
width: 100px;
}
</style>
实现拖拽排序功能
通过 vuedraggable 库可以实现表格行的拖拽排序功能。
<template>
<draggable v-model="rows" tag="tbody" handle=".handle">
<tr v-for="row in rows" :key="row.id">
<td class="handle">↕️</td>
<td>{{ row.name }}</td>
<td>{{ row.age }}</td>
</tr>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
rows: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
以上方法涵盖了从基础到高级的 Vue 表格实现方式,可以根据具体需求选择合适的实现方案。






