vue实现可变表格
Vue实现可变表格的方法
可变表格通常指能够动态增删行列、编辑内容的表格。以下是几种常见的实现方式:
使用v-for动态渲染表格
通过v-for指令结合数组数据动态生成表格行列,配合v-model实现双向绑定:

<template>
<table>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, colIndex) in row" :key="colIndex">
<input v-model="tableData[rowIndex][colIndex]" />
</td>
<td><button @click="removeRow(rowIndex)">删除行</button></td>
</tr>
<button @click="addRow">添加行</button>
<button @click="addColumn">添加列</button>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
['', '', ''],
['', '', '']
]
}
},
methods: {
addRow() {
this.tableData.push(new Array(this.tableData[0].length).fill(''))
},
addColumn() {
this.tableData.forEach(row => row.push(''))
},
removeRow(index) {
this.tableData.splice(index, 1)
}
}
}
</script>
使用第三方表格组件
Element UI的el-table组件提供更丰富的功能:
<template>
<el-table :data="tableData" border>
<el-table-column
v-for="(col, index) in columns"
:key="index"
:prop="col.prop"
:label="col.label">
<template #default="scope">
<el-input v-model="scope.row[col.prop]" />
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-button @click="removeRow(scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-button @click="addRow">添加行</el-button>
<el-button @click="addColumn">添加列</el-button>
</template>
<script>
export default {
data() {
return {
columns: [
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄' }
],
tableData: [
{ name: '', age: '' },
{ name: '', age: '' }
]
}
},
methods: {
addRow() {
this.tableData.push({ name: '', age: '' })
},
addColumn() {
const prop = 'column' + (this.columns.length + 1)
this.columns.push({ prop, label: '新列' })
this.tableData.forEach(row => row[prop] = '')
},
removeRow(index) {
this.tableData.splice(index, 1)
}
}
}
</script>
实现单元格合并
通过计算属性实现动态合并单元格:

computed: {
spanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex % 2 === 0) {
return { rowspan: 2, colspan: 1 }
} else {
return { rowspan: 0, colspan: 0 }
}
}
}
}
实现拖拽排序
使用sortablejs实现行列拖拽排序:
import Sortable from 'sortablejs'
mounted() {
const table = document.querySelector('.el-table__body-wrapper tbody')
Sortable.create(table, {
animation: 150,
onEnd: ({ newIndex, oldIndex }) => {
const movedItem = this.tableData.splice(oldIndex, 1)[0]
this.tableData.splice(newIndex, 0, movedItem)
}
})
}
性能优化建议
对于大数据量表格,建议使用虚拟滚动技术。Element UI的el-table已内置虚拟滚动,只需设置height属性:
<el-table :data="bigData" height="500px">
<!-- 列定义 -->
</el-table>
以上方法可根据实际需求组合使用,实现各种复杂的可变表格功能。






