<basic-table
:data="data"
v-bind="$attrs"
:padding-bottom="80"
v-on="$listeners"
>
// 分页的组件
<select-table-column-by-page
ref="selectColumn"
:data="data"
v-bind="$attrs"
row-key="ID"
v-on="$listeners"
/>
....
</basic-table>
public setCheckAll (val: boolean) {
(this.$refs.selectColumn as SelectTableColumnByPage).setCheckAll(val);
}
SelectTableColumnByPage组件
<template>
<el-table-column
width="50"
>
<template #header>
<el-checkbox
v-model="checkCurrentAll"
:disabled="!(bindData && bindData.length)"
:indeterminate="checkAllIndeterminate"
@change="onCheckCurrentAllChange"
/>
</template>
<template
v-if="bindData[$index]"
slot-scope="{ $index }"
>
<el-checkbox
v-model="bindData[$index].select"
@change="onCheckChange($index, $event)"
/>
</template>
</el-table-column>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Prop, Watch } from 'vue-property-decorator';
@Component
export default class SelectTableColumnByPage extends Vue {
@Prop({
type: Array,
required: true,
default: () => {
return [];
}
})
private data!: any[];
@Prop({
type: String,
required: false,
default: 'id'
})
private rowKey!: string;
@Prop({
type: Array,
required: false
})
private allDataId!: number[];
private selected: number[] = [];
private checkCurrentAll = false;
private checkAllIndeterminate = false;
public setCheckAll (checkAll: boolean) {
if (checkAll) {
this.selected = JSON.parse(JSON.stringify(this.allDataId));
this.checkCurrentAll = true;
this.bindData.forEach(row => {
row.select = true;
});
} else {
this.selected = [];
this.checkCurrentAll = false;
this.bindData.forEach(row => {
row.select = false;
});
}
this.$emit('select', this.selected);
}
// 设置全选
private onCheckCurrentAllChange (val: boolean) {
this.bindData.forEach((row, index) => {
this.onCheckChange(index, val);
});
}
// 单行设置
private onCheckChange (index: number, val: boolean) {
const row = this.bindData[index];
const key = this.getRowKeyValue(row);
const keyIndex = this.selected.indexOf(key);
if (val && keyIndex < 0) {
this.selected.push(key);
}
if (!val && keyIndex > -1) {
this.selected.splice(keyIndex, 1);
}
this.$set(this.bindData[index], 'select', val);
this.setCurrentAllStatus();
this.$emit('select', this.selected);
}
private setCurrentAllStatus () {
this.checkCurrentAll = this.bindData.length ? this.bindData.every(item => item.select) : false;
this.checkAllIndeterminate = this.checkCurrentAll ? false : this.bindData.some(item => item.select);
}
// 更新状态
private checkPageStatus () {
this.bindData.forEach(row => {
row.select = this.selected.findIndex(item => item === row[this.rowKey]) >= 0;
});
this.setCurrentAllStatus();
}
private getRowKeyValue (row) {
return row[this.rowKey];
}
private get bindData () {
return this.data;
}
@Watch('data', { deep: true })
private dataChange () {
this.checkPageStatus();
}
}
</script>
<style lang="scss" scoped></style>