前言

最近两家公司都遇到了全选全页+批量操作的功能场景,即点击全选所有的时候需要勾选所有数据包括非当前页的。
image.png

方案

如果纯前端分页可以参考 antdv.table,一般主流的组件库都给封装好了。
后端分页一种方案是:
基于组件库的现有能力,全选所有时设置 pageSize 为无穷大并调用列表接口得到全量数据赋值给 selectedRowKeys 即可。但是这套方案最大的问题在于点击全选所有时需要等待后端接口返回,这样的交互延迟是无法忍受的!且全选所有+批量操作两次请求的服务端资源浪费也是巨大的。
因此基于后端分页的前提,提出了另一套合理解决方案:
通过 isAll 判断是否为全选所有,如果是的话配合 excludeKeys、否则配合 includeKeys 的值完成返显。最后业务中调用批量操作接口的时候还需要传筛选项 searchParams。

实现

框架为 vue3 + antdv,代码如下:

CTable.vue

<!-- CTable -->
<template>
  <a-table
    v-bind="$attrs"
    :columns="columns"
  >
    <template #headerCell="{ column }" v-if="!$slots.headerCell">
      <template v-if="column.dataIndex === '_checkbox_'">
        <CTableHeaderCheckbox
          ref="cTableHeaderCheckboxRef"
          :rowKey="rowKey"
          :dataSource="dataSource"
          :total="total"
          v-model:isAll="isAll"
          v-model:includeKeys="includeKeys"
          v-model:excludeKeys="excludeKeys"
          :judgeToggleIsAll="judgeToggleIsAll"
        />
      </template>
    </template>
    <template #bodyCell="{ record, column }" v-if="!$slots.bodyCell">
      <template v-if="column.dataIndex === '_checkbox_'">
        <CTableBodyCheckbox
          :record="record"
          :rowKey="rowKey"
          :isAll="isAll"
          :includeKeys="includeKeys"
          :excludeKeys="excludeKeys"
          :judgeToggleIsAll="judgeToggleIsAll"
        />
      </template>
    </template>
    <template v-for="(_, name) in $slots" :key="name" #[name]="slotProps">
      <slot :name="name" v-bind="slotProps" v-if="name === 'headerCell'">
        <CTableHeaderCheckbox
          v-if="slotProps.column.dataIndex === '_checkbox_'"
          ref="cTableHeaderCheckboxRef"
          :rowKey="rowKey"
          :dataSource="dataSource"
          :total="total"
          v-model:isAll="isAll"
          v-model:includeKeys="includeKeys"
          v-model:excludeKeys="excludeKeys"
          :judgeToggleIsAll="judgeToggleIsAll"
        />
      </slot>
      <slot :name="name" v-bind="slotProps" v-if="name === 'bodyCell'">
        <CTableBodyCheckbox
          v-if="slotProps.column.dataIndex === '_checkbox_'"
          :record="slotProps.record"
          :rowKey="rowKey"
          :isAll="isAll"
          :includeKeys="includeKeys"
          :excludeKeys="excludeKeys"
          :judgeToggleIsAll="judgeToggleIsAll"
        />
      </slot>
      <slot :name="name" v-bind="slotProps" v-else></slot>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
import { Table, TableColumnProps } from 'ant-design-vue';
import CTableHeaderCheckbox from './CTableHeaderCheckbox.vue';
import CTableBodyCheckbox from './CTableBodyCheckbox.vue';

const props = withDefaults(
  defineProps<{
    columns: TableColumnProps[],
    allSelection?: {
      onCheckboxChange:(data) => void,
    } | null,
  }>(),
  {
    columns: () => [],
    allSelection: null,
  },
);

const $attrs: any = useAttrs();
const $slots = useSlots();

const cTableHeaderCheckboxRef = ref();
const columns = computed(() => {
  if (props.allSelection) {
    return [
      {
        title: '多选',
        dataIndex: '_checkbox_',
        fixed: 'left',
        width: 48,
        customHeaderCell: () => ({ class: 'ant-table-checkbox-column' }),
      },
      ...props.columns,
    ];
  }
  return props.columns;
});
// 是否全选所有
const isAll = ref(false);
// 未全选所有时勾选数据
const includeKeys = ref<string[]>([]);
// 全选所有时反选数据
const excludeKeys = ref<string[]>([]);
const rowKey = computed(() => $attrs.rowKey || $attrs['row-key']);
const dataSource = computed(() => $attrs.dataSource || $attrs['data-source']);
// 表单数据可能存在disabled不可选择状态,此时需要后端返回enabledTotal帮助判断
const total = computed(() => $attrs.pagination?.enabledTotal || $attrs.pagination?.total || $attrs.enabledTotal || $attrs.total);
// 已勾选总数,帮助业务展示
const checkedTotal = computed(() => (isAll.value ? total.value - excludeKeys.value.length : includeKeys.value.length));
// 当选择数据发生改变时,需要判断是否切换全选状态
const judgeToggleIsAll = () => {
  if (isAll.value && excludeKeys.value.length && excludeKeys.value.length === total.value) {
    isAll.value = false;
    includeKeys.value = [];
    excludeKeys.value = [];
  }
  if (!isAll.value && includeKeys.value.length && includeKeys.value.length === total.value) {
    isAll.value = true;
    includeKeys.value = [];
    excludeKeys.value = [];
  }
};
// 当源数据发生改变时,手动重置选择框状态
const onResetCheckbox = () => {
  cTableHeaderCheckboxRef.value.handleMenu({ key: Table.SELECTION_NONE });
};

// 有任何选择变化时,同步回传给父组件
watch(
  [isAll, includeKeys, excludeKeys],
  () => {
    props.allSelection?.onCheckboxChange?.({
      isAll: isAll.value,
      includeKeys: includeKeys.value,
      excludeKeys: excludeKeys.value,
      checkedTotal: checkedTotal.value,
    });
  },
  { deep: true },
);

defineExpose({
  onResetCheckbox,
});
</script>

<style lang="less" scoped>
.ant-table-wrapper {
  .ant-table {
    &-thead {
      .ant-table-checkbox-column {
        padding-right: 4px;
      }
    }
  }
}
</style>

vue 模版里需要额外判断 slots 是否存在 headerCell 和 bodyCell,如果存在的话透传动态插槽,否则通过具名插槽传入。CTableHeaderCheckbox 使用了 v-model 而 CTableBodyCheckbox 没有使用的原因是 CTableBodyCheckbox 里的操作比较简单,巧妙的利用了数组 splicepush 特性触发响应式对象更新。

CTableHeaderCheckbox.vue

<!-- CTableHeaderCheckbox -->
<template>
  <a-checkbox
    :checked="isCurrentChecked"
    :indeterminate="isCurrentIndeterminate"
    :disabled="isCurrentDisabled"
    @change="onCheckboxChange"
  />
  <a-dropdown
    :disabled="!total"
  >
    <CIcon
      class="ml-2 cursor-pointer"
      icon="triangle-down-o"
      :size="12"
      color="#C9CCD0"
    />
    <template #overlay>
      <a-menu @click="handleMenu">
        <a-menu-item :key="Table.SELECTION_ALL">全选所有</a-menu-item>
        <a-menu-item :key="Table.SELECTION_INVERT">反选当页</a-menu-item>
        <a-menu-item :key="Table.SELECTION_NONE">清空所有</a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
</template>

<script lang="ts" setup>
import { Table } from 'ant-design-vue';

const props = withDefaults(
  defineProps<{
    rowKey: string,
    dataSource: any[],
    isAll: boolean,
    total: number,
    includeKeys: string[],
    excludeKeys: string[],
    judgeToggleIsAll:() => void,
  }>(),
  {},
);
const emit = defineEmits(['update:isAll', 'update:includeKeys', 'update:excludeKeys']);

const dataSourceKeys = computed(() => props.dataSource.filter((record) => !record.disabled).map((item) => item[props.rowKey]));
const isAll = computed({
  get: () => props.isAll,
  set: (val) => {
    emit('update:isAll', val);
  },
});
const includeKeys = computed({
  get: () => props.includeKeys,
  set: (val) => {
    emit('update:includeKeys', val);
  },
});
const excludeKeys = computed({
  get: () => props.excludeKeys,
  set: (val) => {
    emit('update:excludeKeys', val);
  },
});
const isCurrentChecked = computed(() => {
  if (!dataSourceKeys.value.length) return false;
  return isAll.value
    ? !dataSourceKeys.value.some((key) => excludeKeys.value.includes(key))
    : dataSourceKeys.value.every((key) => includeKeys.value.includes(key));
});
const isCurrentIndeterminate = computed(() => {
  if (!dataSourceKeys.value.length) return false;
  if (isAll.value) {
    return !dataSourceKeys.value.every((key) => excludeKeys.value.includes(key)) && !isCurrentChecked.value;
  } else {
    return dataSourceKeys.value.some((key) => includeKeys.value.includes(key)) && !isCurrentChecked.value;
  }
});
const isCurrentDisabled = computed(() => !props.total || props.dataSource.every((record) => record.disabled));
const handleMenu = ({ key }) => {
  if (key === Table.SELECTION_INVERT) {
    // 数学意义的补集
    if (isAll.value) {
      excludeKeys.value = [
        ...excludeKeys.value.filter((excludeKey) => !dataSourceKeys.value.includes(excludeKey)),
        ...dataSourceKeys.value.filter((dataSourceKey) => !excludeKeys.value.includes(dataSourceKey)),
      ];
    } else {
      includeKeys.value = [
        ...includeKeys.value.filter((includeKey) => !dataSourceKeys.value.includes(includeKey)),
        ...dataSourceKeys.value.filter((dataSourceKey) => !includeKeys.value.includes(dataSourceKey)),
      ];
    }
    props.judgeToggleIsAll();
  } else {
    isAll.value = key === Table.SELECTION_ALL;
    includeKeys.value = [];
    excludeKeys.value = [];
  }
};
const onCheckboxChange = (e) => {
  const { checked } = e.target;
  if (isAll.value) {
    excludeKeys.value = checked
      ? excludeKeys.value.filter((key) => !dataSourceKeys.value.includes(key))
      : Array.from(new Set([...excludeKeys.value, ...dataSourceKeys.value]));
  } else {
    includeKeys.value = checked
      ? Array.from(new Set([...includeKeys.value, ...dataSourceKeys.value]))
      : includeKeys.value.filter((key) => !dataSourceKeys.value.includes(key));
  }
  props.judgeToggleIsAll();
};

defineExpose({
  handleMenu,
});
</script>

代码里可以看到 enabledTotal、record.disabled 等字段,这些都是考虑到列表项中有禁用态的数据做的兼容,disabled 是与后端定义好的保留字段,实际封装过程中也可以通过传参 Function(record) => boolean 保持灵活性。

CTableBodyCheckbox.vue

<!-- CTableBodyCheckbox -->
<template>
  <a-checkbox
    :checked="isAll ? !excludeKeys.includes(record[rowKey]) : includeKeys.includes(record[rowKey])"
    :disabled="record.disabled"
    @change="onCheckboxChange(record[rowKey])"
  />
</template>

<script lang="ts" setup>
const props = withDefaults(
  defineProps<{
    record: any,
    rowKey: string,
    isAll: boolean,
    includeKeys: string[],
    excludeKeys: string[],
    judgeToggleIsAll:() => void,
  }>(),
  {},
);

const onCheckboxChange = (key) => {
  const keys = props.isAll ? props.excludeKeys : props.includeKeys;
  const index = keys.indexOf(key);
  if (~index) {
    keys.splice(index, 1);
  } else {
    keys.push(key);
  }
  props.judgeToggleIsAll();
};
</script>

使用

<CTable
  ref="cTableRef"
  :columns
  :dataSource="tableData.dataSource"
  :allSelection
  @change="onTableChange"
/>

const cTableRef = ref();
const allSelection = reactive({
  isAll: false,
  includeKeys: [],
  excludeKeys: [],
  checkedTotal: 0,
  onCheckboxChange: ({
    isAll,
    includeKeys,
    excludeKeys,
    checkedTotal
  }) => {
    allSelection.isAll = isAll;
    allSelection.includeKeys = includeKeys;
    allSelection.excludeKeys = excludeKeys;
    allSelection.checkedTotal = checkedTotal;
  },
});

const batchDelete = () => {
  api({
    isAll: allSelection.isAll,
    includeList: allSelection.includeKeys,
    excludeList: allSelection.excludeKeys,
    ...searchParams,
  }).then(() => {
    cTableRef.value.onResetCheckbox();
  });
};

结论

如此一来,展示和交互逻辑就全部收拢在前端了,对于交互体验和服务端负载都是极大的改善。


小皇帝James
600 声望7 粉丝

IT吴彦祖