vue实现表格多选效果
Vue实现表格多选效果
基础实现方法
使用el-table组件结合type="selection"实现多选
<el-table
ref="multipleTable"
:data="tableData"
@selection-change="handleSelectionChange">
<el-table-column
type="selection"
width="55">
</el-table-column>
<!-- 其他列 -->
</el-table>
在Vue实例中定义相关数据和方法
data() {
return {
tableData: [...], // 表格数据
multipleSelection: [] // 存储选中项
}
},
methods: {
handleSelectionChange(val) {
this.multipleSelection = val;
}
}
自定义选择逻辑
实现跨页选择记忆功能
data() {
return {
selectedRows: new Map() // 使用Map存储选中项
}
},
methods: {
handleSelectionChange(rows) {
rows.forEach(row => {
this.selectedRows.set(row.id, row)
})
},
getRowKey(row) {
return row.id // 确保每行有唯一标识
}
}
在模板中添加row-key属性
<el-table
:row-key="getRowKey"
@selection-change="handleSelectionChange">
</el-table>
全选与反选功能
添加全选按钮控制
methods: {
toggleSelection(rows) {
if (rows) {
rows.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row)
})
} else {
this.$refs.multipleTable.clearSelection()
}
}
}
模板中添加控制按钮
<el-button @click="toggleSelection(tableData)">全选</el-button>
<el-button @click="toggleSelection()">取消选择</el-button>
样式优化
添加选中行高亮样式
.el-table__body tr.current-row>td {
background-color: #f0f7ff;
}
.el-table__body tr.hover-row.current-row>td {
background-color: #e1f0ff;
}
高级功能实现
实现条件选择(只能选择符合特定条件的行)
methods: {
selectable(row, index) {
return row.status === 'active' // 只允许选择状态为active的行
}
}
在模板中使用selectable属性
<el-table-column
type="selection"
:selectable="selectable"
width="55">
</el-table-column>
性能优化
对于大数据量表格使用懒加载选择
data() {
return {
loadedSelections: new Set() // 存储已加载的选中项
}
},
methods: {
loadMoreSelections() {
// 分批加载选中项逻辑
}
}






