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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
<template>
  <!-- 查询表单 -->
  <SearchForm
    v-show="isShowSearch"
    :search="_search"
    :reset="_reset"
    :columns="searchColumns"
    :search-param="searchParam"
    :search-col="12"
  />
 
  <!-- 表格主体 -->
  <div class="card table-main">
    <!-- 表格头部 操作按钮 -->
    <div class="table-header">
      <div class="header-button-lf">
        <slot name="tableHeader" :selected-list="selectedList" :selected-list-ids="selectedListIds" :is-selected="isSelected" />
      </div>
      <div v-if="toolButton" class="header-button-ri">
        <slot name="toolButton">
          <el-button v-if="showToolButton('refresh')" :icon="Refresh" circle @click="getTableList" />
          <el-button v-if="showToolButton('setting') && columns.length" :icon="Operation" circle @click="openColSetting" />
          <el-button
            v-if="showToolButton('search') && searchColumns?.length"
            :icon="Search"
            circle
            @click="isShowSearch = !isShowSearch"
          />
 
          <!-- 新增排版切换按钮 -->
          <el-button v-if="showToolButton('layout')" :icon="layoutType === 'table' ? Grid : List" circle @click="toggleLayout" />
          <el-button v-if="showToolButton('export')" :icon="Download" circle @click="exportData" />
        </slot>
      </div>
    </div>
 
    <!-- 表格排版 -->
    <template v-if="layoutType === 'table'">
      <el-table
        ref="tableRef"
        v-bind="$attrs"
        :id="uuid"
        :data="processTableData"
        :row-key="rowKey"
        @selection-change="selectionChange"
      >
        <!-- 默认插槽 -->
        <slot />
        <template v-for="item in tableColumns" :key="item">
          <!-- selection || radio || index || expand || sort -->
          <el-table-column
            v-if="item.type && columnTypes.includes(item.type)"
            v-bind="item"
            :align="item.align ?? 'center'"
            :reserve-selection="item.type == 'selection'"
          >
            <template #default="scope">
              <!-- expand -->
              <template v-if="item.type == 'expand'">
                <component :is="item.render" v-bind="scope" v-if="item.render" />
                <slot v-else :name="item.type" v-bind="scope" />
              </template>
              <!-- radio -->
              <el-radio v-if="item.type == 'radio'" v-model="radio" :label="scope.row[rowKey]">
                <i></i>
              </el-radio>
              <!-- sort -->
              <el-tag v-if="item.type == 'sort'" class="move">
                <el-icon> <DCaret /></el-icon>
              </el-tag>
            </template>
          </el-table-column>
          <!-- other -->
          <TableColumn v-else :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope" />
            </template>
          </TableColumn>
        </template>
        <!-- 插入表格最后一行之后的插槽 -->
        <template #append>
          <slot name="append" />
        </template>
        <!-- 无数据 -->
        <template #empty>
          <div class="table-empty">
            <slot name="empty">
              <img src="@/assets/images/notData.png" alt="notData" />
              <div>暂无数据</div>
            </slot>
          </div>
        </template>
      </el-table>
    </template>
 
    <!-- 卡片排版 -->
    <template v-else>
      <div class="card-layout">
        <el-row :gutter="cardGutter">
          <el-col v-for="(item, index) in processTableData" :key="item[rowKey]" :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="card-item" :class="{ 'card-item-selected': isSelected(item[rowKey]) }">
              <template #header>
                <div class="card-header">
                  <span>
                    <el-checkbox
                      v-if="showSelection"
                      :model-value="isSelected(item[rowKey])"
                      @change="val => handleCardCheckboxChange(val, item)"
                    />
                  </span>
                  <slot name="Sign" :row="item" :index="index"> </slot>
                </div>
              </template>
              <slot name="Context" :row="item" :index="index"> </slot>
              <template #footer><slot name="Footer" :row="item" :index="index"> </slot></template>
            </el-card>
          </el-col>
        </el-row>
        <!-- 无数据 -->
        <div v-if="!processTableData.length" class="table-empty">
          <slot name="empty">
            <img src="@/assets/images/notData.png" alt="notData" />
            <div>暂无数据</div>
          </slot>
        </div>
      </div>
    </template>
 
    <!-- 分页组件 -->
    <slot name="pagination">
      <Pagination
        v-if="pagination"
        :pageable="pageable"
        :handle-size-change="handleSizeChange"
        :handle-current-change="handleCurrentChange"
      />
    </slot>
  </div>
  <!-- 列设置 -->
  <ColSetting v-if="toolButton && layoutType === 'table'" ref="colRef" v-model:col-setting="colSetting" />
</template>
 
<script setup lang="ts" name="ProTable">
import { ref, watch, provide, onMounted, unref, computed, reactive, nextTick } from "vue";
import { ElTable } from "element-plus";
import { useTable } from "@/hooks/useTable";
import { useSelection } from "@/hooks/useSelection";
import { BreakPoint } from "@/components/Grid/interface";
import { ColumnProps, TypeProps } from "@/components/ProTable/interface";
import { Refresh, Operation, Search, Grid, List, Download } from "@element-plus/icons-vue";
import { generateUUID, handleProp } from "@/utils";
import SearchForm from "@/components/SearchForm/index.vue";
import Pagination from "./components/Pagination.vue";
import ColSetting from "./components/ColSetting.vue";
import TableColumn from "./components/TableColumn.vue";
import Sortable from "sortablejs";
import { ElMessage } from "element-plus";
export interface ProTableProps {
  columns: ColumnProps[]; // 列配置项  ==> 必传
  data?: any[]; // 静态 table data 数据,若存在则不会使用 requestApi 返回的 data ==> 非必传
  requestApi?: (params: any) => Promise<any>; // 请求表格数据的 api ==> 非必传
  requestAuto?: boolean; // 是否自动执行请求 api ==> 非必传(默认为true)
  requestError?: (params: any) => void; // 表格 api 请求错误监听 ==> 非必传
  dataCallback?: (data: any) => any; // 返回数据的回调函数,可以对数据进行处理 ==> 非必传
  title?: string; // 表格标题 ==> 非必传
  pagination?: boolean; // 是否需要分页组件 ==> 非必传(默认为true)
  initParam?: any; // 初始化请求参数 ==> 非必传(默认为{})
  border?: boolean; // 是否带有纵向边框 ==> 非必传(默认为true)
  toolButton?: ("refresh" | "setting" | "search" | "layout" | "export")[] | boolean; // 是否显示表格功能按钮 ==> 非必传(默认为true)
  rowKey?: string; // 行数据的 Key,用来优化 Table 的渲染,当表格数据多选时,所指定的 id ==> 非必传(默认为 id)
  searchCol?: number | Record<BreakPoint, number>; // 表格搜索项 每列占比配置 ==> 非必传 { xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }
  layoutType?: "table" | "card"; // 排版类型 ==> 非必传(默认为table)
  cardGutter?: number; // 卡片间隔 ==> 非必传(默认为16)
  cardColumns?: ColumnProps[]; // 卡片模式下显示的列 ==> 非必传(默认为columns的前4个)
}
 
// 在 ProTableProps 接口中添加导出相关配置
export interface ProTableProps {
  // ...其他属性
  exportFileName?: string; // 导出文件名 ==> 非必传(默认为'表格数据')
  exportMaxSize?: number; // 导出最大数据量 ==> 非必传(默认为10000)
}
 
// 接受父组件参数,配置默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  columns: () => [],
  requestAuto: true,
  pagination: true,
  initParam: {},
  border: true,
  toolButton: true,
  rowKey: "id",
  searchCol: () => ({ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }),
  layoutType: "table",
  cardGutter: 16,
  cardColumns: undefined,
  exportFileName: "表格数据",
  exportMaxSize: 10000
});
 
// 导出方法
const exportData = () => {
  // 获取要导出的数据
  let dataToExport = [];
 
  if (props.data) {
    // 如果有静态数据,使用静态数据
    dataToExport = props.data;
  } else {
    // 否则使用表格数据
    dataToExport = tableData.value;
  }
 
  // 检查数据量是否超过限制
  if (dataToExport.length > props.exportMaxSize) {
    ElMessage.warning(`导出数据量超过限制(最大 ${props.exportMaxSize} 条),请筛选后导出`);
    return;
  }
 
  // 处理导出数据
  const exportColumns = flatColumns.value.filter(col => col.isShow && !columnTypes.includes(col.type!));
 
  // 创建 CSV 内容
  let csvContent = "";
 
  // 添加表头
  const headers = exportColumns.map(col => col.label || col.prop).join(",");
  csvContent += headers + "\n";
 
  // 添加数据行
  dataToExport.forEach(row => {
    const rowData = exportColumns
      .map(col => {
        let value = row[col.prop!];
        // 如果有格式化函数,先格式化
        if (col.formatter) {
          value = col.formatter(row, col, value, 0);
        }
        // 处理枚举值
        if (col.isFilterEnum && col.enum && enumMap.value.has(col.prop!)) {
          const enumData = enumMap.value.get(col.prop!);
          const enumItem = enumData?.find(item => item.value === value);
          value = enumItem?.label ?? value;
        }
        // 处理 CSV 特殊字符
        if (typeof value === "string" && (value.includes(",") || value.includes('"'))) {
          value = `"${value.replace(/"/g, '""')}"`;
        }
        return value ?? "";
      })
      .join(",");
    csvContent += rowData + "\n";
  });
 
  // 创建下载链接
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);
 
  link.href = url;
  link.setAttribute("download", `${props.exportFileName}_${new Date().toISOString().slice(0, 10)}.csv`);
  document.body.appendChild(link);
  link.click();
 
  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
 
  ElMessage.success("导出成功");
};
 
// table 实例
const tableRef = ref<InstanceType<typeof ElTable>>();
 
// 生成组件唯一id
const uuid = ref("id-" + generateUUID());
 
// column 列类型
const columnTypes: TypeProps[] = ["selection", "radio", "index", "expand", "sort"];
 
// 是否显示搜索模块
const isShowSearch = ref(true);
 
// 排版类型
const layoutType = ref(props.layoutType);
 
// 控制 ToolButton 显示
const showToolButton = (key: "refresh" | "setting" | "search" | "layout" | "export") => {
  return Array.isArray(props.toolButton) ? props.toolButton.includes(key) : props.toolButton;
};
 
// 单选值
const radio = ref("");
 
// 表格多选 Hooks
const { selectionChange, selectedList, selectedListIds, isSelected } = useSelection(props.rowKey);
 
// 表格操作 Hooks
const { tableData, pageable, searchParam, searchInitParam, getTableList, search, reset, handleSizeChange, handleCurrentChange } =
  useTable(props.requestApi, props.initParam, props.pagination, props.dataCallback, props.requestError);
 
// 清空选中数据列表
const clearSelection = () => tableRef.value?.clearSelection();
 
// 初始化表格数据 && 拖拽排序
onMounted(() => {
  if (layoutType.value === "table") {
    dragSort();
  }
  props.requestAuto && getTableList();
  props.data && (pageable.value.total = props.data.length);
});
 
// 处理表格数据
const processTableData = computed(() => {
  if (!props.data) return tableData.value;
  if (!props.pagination) return props.data;
  return props.data.slice(
    (pageable.value.pageNum - 1) * pageable.value.pageSize,
    pageable.value.pageSize * pageable.value.pageNum
  );
});
 
// 监听页面 initParam 改化,重新获取表格数据
watch(() => props.initParam, getTableList, { deep: true });
 
// 接收 columns 并设置为响应式
const tableColumns = reactive<ColumnProps[]>(props.columns);
 
// 扁平化 columns
const flatColumns = computed(() => flatColumnsFunc(tableColumns));
 
// 卡片模式下显示的列
// const cardColumns = computed(() => {
//   if (props.cardColumns) return props.cardColumns;
//   // 默认显示前4个非特殊类型的列
//   return flatColumns.value.filter(col => !columnTypes.includes(col.type!)).slice(0, 4);
// });
 
// 是否显示选择框
const showSelection = computed(() => {
  return flatColumns.value.some(col => col.type === "selection");
});
 
// 定义 enumMap 存储 enum 值(避免异步请求无法格式化单元格内容 || 无法填充搜索下拉选择)
const enumMap = ref(new Map<string, { [key: string]: any }[]>());
const setEnumMap = async ({ prop, enum: enumValue }: ColumnProps) => {
  if (!enumValue) return;
 
  // 如果当前 enumMap 存在相同的值 return
  if (enumMap.value.has(prop!) && (typeof enumValue === "function" || enumMap.value.get(prop!) === enumValue)) return;
 
  // 当前 enum 为静态数据,则直接存储到 enumMap
  if (typeof enumValue !== "function") return enumMap.value.set(prop!, unref(enumValue!));
 
  // 为了防止接口执行慢,而存储慢,导致重复请求,所以预先存储为[],接口返回后再二次存储
  enumMap.value.set(prop!, []);
 
  // 当前 enum 为后台数据需要请求数据,则调用该请求接口,并存储到 enumMap
  const { data } = await enumValue();
  enumMap.value.set(prop!, data);
};
 
// 注入 enumMap
provide("enumMap", enumMap);
 
// 扁平化 columns 的方法
const flatColumnsFunc = (columns: ColumnProps[], flatArr: ColumnProps[] = []) => {
  columns.forEach(async col => {
    if (col._children?.length) flatArr.push(...flatColumnsFunc(col._children));
    flatArr.push(col);
 
    // column 添加默认 isShow && isSetting && isFilterEnum 属性值
    col.isShow = col.isShow ?? true;
    col.isSetting = col.isSetting ?? true;
    col.isFilterEnum = col.isFilterEnum ?? true;
 
    // 设置 enumMap
    await setEnumMap(col);
  });
  return flatArr.filter(item => !item._children?.length);
};
 
// 过滤需要搜索的配置项 && 排序
const searchColumns = computed(() => {
  return flatColumns.value
    ?.filter(item => item.search?.el || item.search?.render)
    .sort((a, b) => a.search!.order! - b.search!.order!);
});
 
// 设置 搜索表单默认排序 && 搜索表单项的默认值
searchColumns.value?.forEach((column, index) => {
  column.search!.order = column.search?.order ?? index + 2;
  const key = column.search?.key ?? handleProp(column.prop!);
  const defaultValue = column.search?.defaultValue;
  if (defaultValue !== undefined && defaultValue !== null) {
    searchParam.value[key] = defaultValue;
    searchInitParam.value[key] = defaultValue;
  }
});
 
// 列设置 ==> 需要过滤掉不需要设置的列
const colRef = ref();
const colSetting = tableColumns!.filter(item => {
  const { type, prop, isSetting } = item;
  return !columnTypes.includes(type!) && prop !== "operation" && isSetting;
});
const openColSetting = () => colRef.value.openColSetting();
 
// 定义 emit 事件
const emit = defineEmits<{
  search: [];
  reset: [];
  dragSort: [{ newIndex?: number; oldIndex?: number }];
  cardClick: [row: any];
  layoutChange: [type: "table" | "card"];
}>();
 
const _search = () => {
  search();
  emit("search");
};
 
const _reset = () => {
  reset();
  emit("reset");
};
 
// 切换排版类型
const toggleLayout = () => {
  // 同步选择状态
  if (layoutType.value === "table") {
    // 表格 -> 卡片:同步表格的选中状态到卡片
    const selection = tableRef.value?.getSelectionRows() || [];
    selectionChange(selection);
  } else {
    // 卡片 -> 表格:同步卡片的选中状态到表格
    nextTick(() => {
      if (tableRef.value) {
        tableRef.value.clearSelection();
        const selectedRows = processTableData.value.filter(row => isSelected(row[props.rowKey]));
        selectedRows.forEach(row => {
          tableRef.value?.toggleRowSelection(row, true);
        });
      }
    });
  }
 
  layoutType.value = layoutType.value === "table" ? "card" : "table";
  emit("layoutChange", layoutType.value);
};
 
// // 卡片点击事件
// const handleCardClick = (row: any) => {
//   emit("cardClick", row);
// };
 
// 卡片复选框变化
const handleCardCheckboxChange = (checked: boolean, row: any) => {
  const currentSelection = [...selectedList.value];
  if (checked) {
    currentSelection.push(row);
  } else {
    const index = currentSelection.findIndex(item => item[props.rowKey] === row[props.rowKey]);
    if (index !== -1) {
      currentSelection.splice(index, 1);
    }
  }
  selectionChange(currentSelection);
};
 
// 表格拖拽排序
const dragSort = () => {
  if (layoutType.value !== "table") return;
 
  const tbody = document.querySelector(`#${uuid.value} tbody`) as HTMLElement;
  if (!tbody) return;
 
  Sortable.create(tbody, {
    handle: ".move",
    animation: 300,
    onEnd({ newIndex, oldIndex }) {
      const [removedItem] = processTableData.value.splice(oldIndex!, 1);
      processTableData.value.splice(newIndex!, 0, removedItem);
      emit("dragSort", { newIndex, oldIndex });
    }
  });
};
 
// 监听排版类型变化
watch(layoutType, newVal => {
  if (newVal === "table") {
    nextTick(() => {
      dragSort();
    });
  }
});
 
// 暴露给父组件的参数和方法 (外部需要什么,都可以从这里暴露出去)
defineExpose({
  element: tableRef,
  tableData: processTableData,
  radio,
  pageable,
  searchParam,
  searchInitParam,
  isSelected,
  selectedList,
  selectedListIds,
  layoutType,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  clearSelection,
  enumMap,
  toggleLayout
});
</script>
 
<style lang="scss" scoped>
.card-layout {
  padding: 10px;
}
.card-item {
  padding: 16px;
  margin-bottom: 16px;
  cursor: pointer;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 12%);
  transition: all 0.3s;
  &:hover {
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }
  &-selected {
    background-color: rgba(var(--el-color-primary-rgb), 0.05);
    border: 1px solid var(--el-color-primary);
  }
  &-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
  }
  &-content {
    > * + * {
      margin-top: 8px;
    }
  }
  &-field {
    display: flex;
    font-size: 14px;
  }
  &-label {
    flex-shrink: 0;
    margin-right: 8px;
    color: #666666;
  }
  &-value {
    flex: 1;
    word-break: break-all;
  }
}
.card-actions {
  display: flex;
  gap: 8px;
}
</style>