zhitong.yu
8 天以前 378d781e6f35f89652aa36e079a8b7fc44cea77e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { ref, computed } from "vue";
 
/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时,所指定的 id
 * */
export const useSelection = (rowKey: string = "id") => {
  // 必须明确标注返回的函数类型
  const isSelected = (id: string): boolean => {
    return selectedListIds.value.includes(id);
  };
  const selectedList = ref<{ [key: string]: any }[]>([]);
 
  // 当前选中的所有 ids 数组
  const selectedListIds = computed((): string[] => {
    let ids: string[] = [];
    selectedList.value.forEach(item => ids.push(item[rowKey]));
    return ids;
  });
 
  /**
   * @description 多选操作
   * @param {Array} rowArr 当前选择的所有数据
   * @return void
   */
  const selectionChange = (rowArr: { [key: string]: any }[]) => {
    rowArr.length ? (isSelected.value = true) : (isSelected.value = false);
    selectedList.value = rowArr;
  };
 
  return {
    isSelected,
    selectedList,
    selectedListIds,
    selectionChange
  };
};