vue中使用el-table组件checkbox进行分页多选,回显、切换分页记住上一页所勾选和取消的选项
<template>
<el-dialog title="新增/编辑" :visible.sync="dialogVisible" width="60%" :before-close="handleClose" :destroy-on-close="false" :close-on-click-modal="false">
<el-table :data="companyData" v-loading="companyLoading" height="300" ref="multipleTable" @select="handleSelectionChange" @select-all="handleAllChange" :row-key="(row)=>{ return row.companyId}">
<el-table-column label="全选" type="selection" width="55" :reserve-selection="true"></el-table-column>
<el-table-column prop="companyName" label="企业名称" />
</el-table>
<div class="pagination" style='text-align: right; margin-top: 10px'>
<element-pagination :page-size="pagination.size" :current-page="pagination.page" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
</div>
</el-dialog>
</template>
<script>
export default {
data () {
return {
dialogVisible: false,
companyData: [],
selectList: [],
companyLoading: false,
pagination: {
page: 1,
size: 20
},
total: 0,
}
},
methods: {
show (id) {
this.dialogVisible = true
this.getDetail()
},
// 获取详情
async getDetail () {
const res = await this.$http.get('/api/detail?id=1')
this.selectList = res.companyIdList
},
handleSizeChange (size) {
this.pagination.size = size
this.getList()
},
handleCurrentChange (page) {
this.pagination.page = page
this.getList()
},
// 获取数据
async getList () {
try {
this.companyLoading = true
const { page, size } = this.pagination
const params = {
url: '/api/search',
params: {
page: page - 1,
size,
like_companyName: this.value2
}
}
const { rows = [], total = 0 } = await this.$http(params)
this.companyLoading = false
this.companyData = rows
this.total = total
setTimeout(() => {
if (this.selectList.length > 0) {
this.echo(rows)
}
}, 10);
} catch (error) {
console.log(error)
} finally {
this.companyLoading = false
}
},
echo (data) {
let rows = []
data.forEach(item => {
this.selectList.forEach(item2 => {
if (item.companyId === item2) {
rows.push(item)
}
})
})
this.toggleSelection(rows)
},
// 在获取企业数据下调用
toggleSelection (rows) {
if (rows) {
rows.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row, true)
})
} else {
this.$refs.multipleTable.clearSelection()
}
},
// 选择企业, 打钩或者取消
handleSelectionChange (selecteds, row) {
// console.log(selecteds, row)
if (!this.selectList.includes(row.companyId)) {
// 回显数据里没有本条, 把这条加进来(选中)
this.selectList.push(row.companyId)
} else {
// 回显数据有本条,把这条数据删除(取消选中)
this.selectList.splice(this.selectList.indexOf(row.companyId), 1)
}
},
// 全选、取消全选
handleAllChange (selects) {
// console.log(selects)
if (selects.length > 0) {
selects.forEach(item => {
if (!this.selectList.includes(item.companyId)) {
this.selectList.push(item.companyId)
}
})
} else {
this.companyData.list.forEach(item => {
this.selectList.forEach((id, index) => {
if (item.companyId === id) {
this.selectList.splice(index, 1)
}
})
})
}
},
}
}
</script>
<style lang="scss" scoped>
</style>