1、在使用 vue + element-ui 开发后台管理类型的页面时,有这样一个需求
- 表格每一行添加复选框,可以被选择
- 切换页码时,要保存上一页的复选框的选中状态
2、通过代码实现
给表格的某一列添加 type=“selection”,这一列就添加了复选框
<el-table-column type="selection" width="55" align="center"></el-table-column>
有了复选框,我们需要获取用户选择了哪些行数据,给表格添加两个事件:
- select-all:全选按钮事件
- select:单个复选框事件
<el-table :data="tableData" ref="table" @select-all="selectAllRow" @select="selectCheckBox">
<el-table-column type="selection" width="55" align="center"></el-table-column>
</el-table>
定义上面两个事件的处理函数
data(){
return {
tableData: [], // 表格数据
current: 1, // 页码
selectRowAry: [], // 二维数组,保存每一页选中的行
}
},
methods: {
// 全选按钮事件
selectAllRow(selection){
/**
* @param {Array} selection:当前页全选 / 取消全选后的结果
*/
this.selectRowAry[this.current] = selection
},
// 单个复选框事件
selectCheckBox(selection){
/**
* @param {Array} selection:当前页所有选中的复选框的结果
*/
this.selectRowAry[this.current] = selection
},
},
当切换页码时,需要设置当前页的复选框的选中状态,需要在 vue 的 update 生命周期函数中实现,数据更新需要时间,所以在 $nextTick 中实现,这里还用到 element-ui table 组件的 toggleRowSelection 事件
- toggleRowSelection(row, selection):两个参数, row:需要设置的行, selection:需要设置的状态
- 还需要注意一点:toggleRowSelection设置的行必须是获取的原始数据中的行(直接从接口中获取的数据 tableData)
updated(){
// 切换页码时, 设置复选框的选中状态
this.$nextTick(()=>{
this.tableData.forEach(el=>{
this.selectRowAry[this.current] && this.selectRowAry[this.current].forEach(item=>{
// 这里 toggleRowSelection 的第一个参数必须是 el,设置 item 无效
if(el.id === item.id) this.$refs['table'].toggleRowSelection(el, true)
})
})
})
},
如果需要导出每一页中选择的行数据,使用 selectRowAry 即可