实现效果: 点击某一页的全选后,仅当前页全选,切换到其他分页后,再切回之前选中的页面,选择的值还在
<script>
export default {
data(){
return{
// 表格数据
tableData: [],
// 已选中数据
checkedList: []
}
},
watch: {
// 切换分页时,将已存在的数据勾选
tableData(newVal) {
if (!newVal || !newVal.length)return
const checkedId = []
this.checkedList.forEach(item => {
checkedId.push(item.id)
})
setTimeout(() => {
this.tableData.forEach(item => {
if(checkedId.includes(item.id)) {
this.$refs.table.toggleRowSelection(item)
}
})
})
}
},
methods: {
selectOne(value, row) {
// 判定当前点击的行是选中还是取消
if (value.length) {
// value存在时,当前行是否在value中,不存在result为undefind
const result = value.find(v => v.id === row.id)
if (result) {
// 选中当前行,将当前行push到checkedList中
this.checkedList.push(result)
} else {
// 取消当前行,将当前行从checkedList中删除
this.checkedList = this.checkedList.filter(v => v.id === row.id)
}
} else {
// value不存在时将当前行从选中列表中删除
this.checkedList = this.checkedList.filter(v => v.id === row.id)
}
},
selectAll(value) {
if(value.length === this.tableData.length) {
// 选中全选
if(this.checkedList.length) {
// 已有选中数据,将checkedList中已存在的选项过滤掉,将不存在的选项合并到checkedList
// 从checkedList 获取已选中的数据的id
const checkedId = []
this.checkedList.forEach(item => {
checkedId.push(item.id)
})
// 过滤掉全选的数据中在checkedList中已存在的数据
const newChecked = value.filter(i => !checkedId.includes(i.id))
// 将新选中的数据合并到checkedList
this.checkedList = [...this.checkedList, ...newChecked]
} else {
// checkedList为空,将当前页的数据直接赋值给checkedList
this.checkedList = this.tableData
}
}else {
// 取消全选,将当前页数据从checkedList过滤掉
const checkedId = []
this.checkedList.forEach(item => {
checkedId.push(item.id)
})
this.checkedList = this.checkedList.filter(i => !checkedId.includes(i.id))
}
}
}
}
</script>