vue表格动态实现
Vue 动态表格实现方法
基于 v-for 的静态数据渲染
动态表格的核心是通过 v-for 循环渲染数据。定义表格数据为响应式数组,通过方法动态修改数据即可实现更新。
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in tableData" :key="index">
<td v-for="col in columns" :key="col">{{ row[col] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
columns: ['name', 'age', 'gender'],
tableData: [
{ name: 'Alice', age: 25, gender: 'Female' },
{ name: 'Bob', age: 30, gender: 'Male' }
]
}
}
}
</script>
动态列与行控制
通过计算属性或方法动态生成列信息,支持字段的增删改查。

methods: {
addColumn(colName) {
if (!this.columns.includes(colName)) {
this.columns.push(colName)
this.tableData.forEach(row => {
row[colName] = '' // 初始化新列
})
}
},
removeColumn(colName) {
const index = this.columns.indexOf(colName)
if (index > -1) {
this.columns.splice(index, 1)
this.tableData.forEach(row => {
delete row[colName]
})
}
}
}
服务端数据加载
结合 axios 等库实现异步数据加载,注意处理加载状态。

data() {
return {
loading: false,
tableData: []
}
},
async created() {
this.loading = true
try {
const res = await axios.get('/api/data')
this.tableData = res.data
} finally {
this.loading = false
}
}
高级功能实现
可编辑单元格:通过动态切换 input 和文本显示
<td @dblclick="editCell(row, col)">
<input v-if="row.editing === col"
v-model="row[col]"
@blur="saveEdit(row)">
<span v-else>{{ row[col] }}</span>
</td>
动态排序:使用计算属性实现
computed: {
sortedData() {
return [...this.tableData].sort((a, b) => {
return a[this.sortBy] > b[this.sortBy] ? 1 : -1
})
}
}
性能优化建议
- 大数据量使用虚拟滚动(如 vue-virtual-scroller)
- 复杂表格考虑专业组件库(如 Element UI 的 el-table)
- 使用
:key时避免索引,采用唯一 ID - 分页加载减少初始渲染压力
完整示例
<template>
<div>
<button @click="addRandomRow">Add Row</button>
<table>
<thead>
<tr>
<th v-for="col in columns"
:key="col"
@click="sortBy(col)">
{{ col }} {{ sortBy === col ? (sortDesc ? '↓' : '↑') : '' }}
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="row in sortedData" :key="row.id">
<td v-for="col in columns" :key="col">
<EditableCell :value="row[col]" @update="val => updateCell(row, col, val)"/>
</td>
<td><button @click="removeRow(row.id)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import EditableCell from './EditableCell.vue'
export default {
components: { EditableCell },
data() {
return {
columns: ['id', 'name', 'value'],
tableData: [],
sortBy: 'id',
sortDesc: false,
nextId: 1
}
},
computed: {
sortedData() {
return [...this.tableData].sort((a, b) => {
const valA = a[this.sortBy]
const valB = b[this.sortBy]
return this.sortDesc ? valB - valA : valA - valB
})
}
},
methods: {
addRandomRow() {
this.tableData.push({
id: this.nextId++,
name: `Item ${this.nextId}`,
value: Math.floor(Math.random() * 100)
})
},
removeRow(id) {
this.tableData = this.tableData.filter(row => row.id !== id)
},
sortBy(col) {
if (this.sortBy === col) {
this.sortDesc = !this.sortDesc
} else {
this.sortBy = col
this.sortDesc = false
}
},
updateCell(row, col, val) {
row[col] = val
}
}
}
</script>





