index.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. <template>
  2. <!-- 表格主体 -->
  3. <div class="card table-main">
  4. <!-- 表格头部 操作按钮 -->
  5. <div class="table-header">
  6. <div class="header-button-lf">
  7. <slot name="tableHeader" :selected-list="selectedList" :selected-list-ids="selectedListIds" :is-selected="isSelected" />
  8. </div>
  9. <div v-if="toolButton" class="header-button-ri">
  10. <slot name="toolButton">
  11. <img
  12. class="setting"
  13. src="@/assets/images/setting.png"
  14. v-if="showToolButton('setting') && columns.length"
  15. @click="openColSetting"
  16. />
  17. </slot>
  18. </div>
  19. </div>
  20. <!-- 表格主体 -->
  21. <el-table
  22. stripe
  23. ref="tableRef"
  24. v-bind="$attrs"
  25. :id="uuid"
  26. :data="processTableData"
  27. :border="border"
  28. :row-key="rowKey"
  29. @selection-change="selectionChange"
  30. >
  31. <!-- 默认插槽 -->
  32. <slot />
  33. <template v-for="item in tableColumns" :key="item">
  34. <!-- selection || radio || index || expand || sort -->
  35. <el-table-column
  36. v-if="item.type && columnTypes.includes(item.type)"
  37. v-bind="item"
  38. :align="item.align ?? 'left'"
  39. :reserve-selection="item.type == 'selection'"
  40. >
  41. <template #default="scope">
  42. <!-- expand -->
  43. <template v-if="item.type == 'expand'">
  44. <component :is="item.render" v-bind="scope" v-if="item.render" />
  45. <slot v-else :name="item.type" v-bind="scope" />
  46. </template>
  47. <!-- radio -->
  48. <el-radio v-if="item.type == 'radio'" v-model="radio" :label="scope.row[rowKey]">
  49. <i></i>
  50. </el-radio>
  51. <!-- sort -->
  52. <el-tag v-if="item.type == 'sort'" class="move">
  53. <el-icon> <DCaret /></el-icon>
  54. </el-tag>
  55. </template>
  56. </el-table-column>
  57. <!-- other -->
  58. <TableColumn v-else :column="item">
  59. <template v-for="slot in Object.keys($slots)" #[slot]="scope">
  60. <slot :name="slot" v-bind="scope" />
  61. </template>
  62. </TableColumn>
  63. </template>
  64. <!-- 插入表格最后一行之后的插槽 -->
  65. <template #append>
  66. <slot name="append" />
  67. </template>
  68. <!-- 无数据 -->
  69. <template #empty>
  70. <div class="table-empty">
  71. <slot name="empty">
  72. <img src="@/assets/images/notData.png" alt="notData" />
  73. <div>暂无数据</div>
  74. </slot>
  75. </div>
  76. </template>
  77. </el-table>
  78. <!-- 分页组件 -->
  79. <slot name="pagination">
  80. <Pagination
  81. v-if="pagination"
  82. :pageable="pageable"
  83. :handle-size-change="handleSizeChange"
  84. :handle-current-change="handleCurrentChange"
  85. />
  86. </slot>
  87. </div>
  88. <!-- 列设置 -->
  89. <ColSetting v-if="toolButton" ref="colRef" v-model:col-setting="colSetting" />
  90. </template>
  91. <script setup lang="ts" name="ProTable">
  92. import { ref, watch, provide, onMounted, unref, computed, reactive } from "vue";
  93. import { ElTable } from "element-plus";
  94. import { useTable } from "@/hooks/useTable";
  95. import { useSelection } from "@/hooks/useSelection";
  96. import { BreakPoint } from "@/components/Grid/interface";
  97. import { ColumnProps, TypeProps } from "@/components/ProTable/interface";
  98. import { generateUUID, handleProp } from "@/utils";
  99. import Pagination from "./components/Pagination.vue";
  100. import ColSetting from "./components/ColSetting.vue";
  101. import TableColumn from "./components/TableColumn.vue";
  102. import Sortable from "sortablejs";
  103. export interface ProTableProps {
  104. columns: ColumnProps[]; // 列配置项 ==> 必传
  105. data?: any[]; // 静态 table data 数据,若存在则不会使用 requestApi 返回的 data ==> 非必传
  106. requestApi?: (params: any) => Promise<any>; // 请求表格数据的 api ==> 非必传
  107. requestAuto?: boolean; // 是否自动执行请求 api ==> 非必传(默认为true)
  108. requestError?: (params: any) => void; // 表格 api 请求错误监听 ==> 非必传
  109. dataCallback?: (data: any) => any; // 返回数据的回调函数,可以对数据进行处理 ==> 非必传
  110. title?: string; // 表格标题 ==> 非必传
  111. pagination?: boolean; // 是否需要分页组件 ==> 非必传(默认为true)
  112. initParam?: any; // 初始化请求参数 ==> 非必传(默认为{})
  113. border?: boolean; // 是否带有纵向边框 ==> 非必传(默认为true)
  114. toolButton?: "setting"[] | boolean; // 是否显示表格功能按钮 ==> 非必传(默认为true)
  115. rowKey?: string; // 行数据的 Key,用来优化 Table 的渲染,当表格数据多选时,所指定的 id ==> 非必传(默认为 id)
  116. searchCol?: number | Record<BreakPoint, number>; // 表格搜索项 每列占比配置 ==> 非必传 { xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }
  117. }
  118. // 接受父组件参数,配置默认值
  119. const props = withDefaults(defineProps<ProTableProps>(), {
  120. columns: () => [],
  121. requestAuto: true,
  122. pagination: true,
  123. initParam: {},
  124. border: true,
  125. toolButton: true,
  126. rowKey: "id",
  127. searchCol: () => ({ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 })
  128. });
  129. // table 实例
  130. const tableRef = ref<InstanceType<typeof ElTable>>();
  131. // 生成组件唯一id
  132. const uuid = ref("id-" + generateUUID());
  133. // column 列类型
  134. const columnTypes: TypeProps[] = ["selection", "radio", "index", "expand", "sort"];
  135. // 控制 ToolButton 显示
  136. const showToolButton = (key: "refresh" | "setting" | "search") => {
  137. return Array.isArray(props.toolButton) ? props.toolButton.includes(key) : props.toolButton;
  138. };
  139. // 单选值
  140. const radio = ref("");
  141. // 表格多选 Hooks
  142. const { selectionChange, selectedList, selectedListIds, isSelected } = useSelection(props.rowKey);
  143. // 表格操作 Hooks
  144. const { tableData, pageable, searchParam, searchInitParam, getTableList, search, reset, handleSizeChange, handleCurrentChange } =
  145. useTable(props.requestApi, props.initParam, props.pagination, props.dataCallback, props.requestError);
  146. // 清空选中数据列表
  147. const clearSelection = () => tableRef.value!.clearSelection();
  148. // 初始化表格数据 && 拖拽排序
  149. onMounted(() => {
  150. dragSort();
  151. props.requestAuto && getTableList();
  152. props.data && (pageable.value.total = props.data.length);
  153. });
  154. // 处理表格数据
  155. const processTableData = computed(() => {
  156. if (!props.data) return tableData.value;
  157. if (!props.pagination) return props.data;
  158. return props.data.slice(
  159. (pageable.value.pageNum - 1) * pageable.value.pageSize,
  160. pageable.value.pageSize * pageable.value.pageNum
  161. );
  162. });
  163. // 监听页面 initParam 改化,重新获取表格数据
  164. watch(() => props.initParam, getTableList, { deep: true });
  165. // 接收 columns 并设置为响应式
  166. const tableColumns = reactive<ColumnProps[]>(props.columns);
  167. // 扁平化 columns
  168. const flatColumns = computed(() => flatColumnsFunc(tableColumns));
  169. // 定义 enumMap 存储 enum 值(避免异步请求无法格式化单元格内容 || 无法填充搜索下拉选择)
  170. const enumMap = ref(new Map<string, { [key: string]: any }[]>());
  171. const setEnumMap = async ({ prop, enum: enumValue }: ColumnProps) => {
  172. if (!enumValue) return;
  173. // 如果当前 enumMap 存在相同的值 return
  174. if (enumMap.value.has(prop!) && (typeof enumValue === "function" || enumMap.value.get(prop!) === enumValue)) return;
  175. // 当前 enum 为静态数据,则直接存储到 enumMap
  176. if (typeof enumValue !== "function") return enumMap.value.set(prop!, unref(enumValue!));
  177. // 为了防止接口执行慢,而存储慢,导致重复请求,所以预先存储为[],接口返回后再二次存储
  178. enumMap.value.set(prop!, []);
  179. // 当前 enum 为后台数据需要请求数据,则调用该请求接口,并存储到 enumMap
  180. const { data } = await enumValue();
  181. enumMap.value.set(prop!, data);
  182. };
  183. // 注入 enumMap
  184. provide("enumMap", enumMap);
  185. // 扁平化 columns 的方法
  186. const flatColumnsFunc = (columns: ColumnProps[], flatArr: ColumnProps[] = []) => {
  187. columns.forEach(async col => {
  188. if (col._children?.length) flatArr.push(...flatColumnsFunc(col._children));
  189. flatArr.push(col);
  190. // column 添加默认 isShow && isSetting && isFilterEnum 属性值
  191. col.isShow = col.isShow ?? true;
  192. col.isSetting = col.isSetting ?? true;
  193. col.isFilterEnum = col.isFilterEnum ?? true;
  194. // 设置 enumMap
  195. await setEnumMap(col);
  196. });
  197. return flatArr.filter(item => !item._children?.length);
  198. };
  199. // 过滤需要搜索的配置项 && 排序
  200. const searchColumns = computed(() => {
  201. return flatColumns.value
  202. ?.filter(item => item.search?.el || item.search?.render)
  203. .sort((a, b) => a.search!.order! - b.search!.order!);
  204. });
  205. // 设置 搜索表单默认排序 && 搜索表单项的默认值
  206. searchColumns.value?.forEach((column, index) => {
  207. column.search!.order = column.search?.order ?? index + 2;
  208. const key = column.search?.key ?? handleProp(column.prop!);
  209. const defaultValue = column.search?.defaultValue;
  210. if (defaultValue !== undefined && defaultValue !== null) {
  211. searchParam.value[key] = defaultValue;
  212. searchInitParam.value[key] = defaultValue;
  213. }
  214. });
  215. // 列设置 ==> 需要过滤掉不需要设置的列
  216. const colRef = ref();
  217. const colSetting = tableColumns!.filter(item => {
  218. const { type, prop, isSetting } = item;
  219. return !columnTypes.includes(type!) && prop !== "operation" && isSetting;
  220. });
  221. const openColSetting = () => colRef.value.openColSetting();
  222. // 定义 emit 事件
  223. const emit = defineEmits<{
  224. search: [];
  225. reset: [];
  226. dragSort: [{ newIndex?: number; oldIndex?: number }];
  227. }>();
  228. // 表格拖拽排序
  229. const dragSort = () => {
  230. const tbody = document.querySelector(`#${uuid.value} tbody`) as HTMLElement;
  231. Sortable.create(tbody, {
  232. handle: ".move",
  233. animation: 300,
  234. onEnd({ newIndex, oldIndex }) {
  235. const [removedItem] = processTableData.value.splice(oldIndex!, 1);
  236. processTableData.value.splice(newIndex!, 0, removedItem);
  237. emit("dragSort", { newIndex, oldIndex });
  238. }
  239. });
  240. };
  241. // 暴露给父组件的参数和方法 (外部需要什么,都可以从这里暴露出去)
  242. defineExpose({
  243. element: tableRef,
  244. tableData: processTableData,
  245. radio,
  246. pageable,
  247. searchParam,
  248. searchInitParam,
  249. isSelected,
  250. selectedList,
  251. selectedListIds,
  252. // 下面为 function
  253. getTableList,
  254. search,
  255. reset,
  256. handleSizeChange,
  257. handleCurrentChange,
  258. clearSelection,
  259. enumMap
  260. });
  261. </script>
  262. <style>
  263. .setting {
  264. height: 20px;
  265. width: 20px;
  266. margin-top: 10px;
  267. margin-right: 5px;
  268. cursor: pointer;
  269. }
  270. </style>