vue实现表格多选效果
实现表格多选的基础方法
使用 Vue 的 v-model 绑定到复选框,结合 v-for 渲染表格数据。在数据中增加 selected 属性标记选中状态。
<template>
<table>
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td><input type="checkbox" v-model="item.selected"></td>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Item 1', selected: false },
{ id: 2, name: 'Item 2', selected: false }
],
selectAll: false
}
}
}
</script>
全选/反选功能实现
通过计算属性或监听器实现全选逻辑。当点击全选复选框时,同步所有行的选中状态。
watch: {
selectAll(newVal) {
this.tableData.forEach(item => {
item.selected = newVal
})
}
}
获取选中项数据
添加方法获取当前选中的数据,通过过滤 selected 为 true 的项。
methods: {
getSelectedItems() {
return this.tableData.filter(item => item.selected)
}
}
使用第三方组件库优化
Element UI 或 Ant Design Vue 等库提供现成的多选表格组件。
<!-- Element UI 示例 -->
<el-table
:data="tableData"
@selection-change="handleSelectionChange">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="id" label="ID"></el-table-column>
</el-table>
<script>
export default {
methods: {
handleSelectionChange(val) {
this.selectedItems = val
}
}
}
</script>
性能优化建议
对于大数据量表格,使用虚拟滚动或分页加载。避免直接绑定大量数据的响应式属性,可采用非响应式数据配合手动更新。
// 使用 Object.freeze 冻结非响应式数据
this.tableData = Object.freeze(largeDataArray)






