useListPage.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { reactive, ref, Ref, unref } from 'vue';
  2. import { merge } from 'lodash-es';
  3. import { DynamicProps } from '/#/utils';
  4. import { BasicTableProps, TableActionType, useTable } from '/@/components/Table';
  5. import { ColEx } from '/@/components/Form/src/types';
  6. import { FormActionType } from '/@/components/Form';
  7. import { useMessage } from '/@/hooks/web/useMessage';
  8. import { useMethods } from '/@/hooks/system/useMethods';
  9. import { useDesign } from '/@/hooks/web/useDesign';
  10. import { filterObj } from '/@/utils/common/compUtils';
  11. const { handleExportXls, handleImportXls } = useMethods();
  12. // 定义 useListPage 方法所需参数
  13. interface ListPageOptions {
  14. // 样式作用域范围
  15. designScope?: string;
  16. // 【必填】表格参数配置
  17. tableProps: TableProps;
  18. // 分页
  19. pagination?: boolean;
  20. // 导出配置
  21. exportConfig?: {
  22. url: string | (() => string);
  23. // 导出文件名
  24. name?: string | (() => string);
  25. //导出参数
  26. params?: object;
  27. };
  28. // 导入配置
  29. importConfig?: {
  30. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  31. url: string | (() => string);
  32. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  33. // 导出成功后的回调
  34. success?: (fileInfo?: any) => void;
  35. };
  36. }
  37. interface IDoRequestOptions {
  38. // 是否显示确认对话框,默认 true
  39. confirm?: boolean;
  40. // 是否自动刷新表格,默认 true
  41. reload?: boolean;
  42. // 是否自动清空选择,默认 true
  43. clearSelection?: boolean;
  44. }
  45. /**
  46. * listPage页面公共方法
  47. *
  48. * @param options
  49. */
  50. export function useListPage(options: ListPageOptions) {
  51. const $message = useMessage();
  52. let $design = {} as ReturnType<typeof useDesign>;
  53. if (options.designScope) {
  54. $design = useDesign(options.designScope);
  55. }
  56. const tableContext = useListTable(options.tableProps);
  57. const [, { getForm, reload, setLoading }, { selectedRowKeys }] = tableContext;
  58. // 导出 excel
  59. async function onExportXls() {
  60. //update-begin---author:wangshuai ---date:20220411 for:导出新增自定义参数------------
  61. let { url, name, params } = options?.exportConfig ?? {};
  62. let realUrl = typeof url === 'function' ? url() : url;
  63. if (realUrl) {
  64. let title = typeof name === 'function' ? name() : name;
  65. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导出报错,原因未知-
  66. let paramsForm = {};
  67. try {
  68. paramsForm = await getForm().validate();
  69. } catch (e) {
  70. console.error(e);
  71. }
  72. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导出报错,原因未知-
  73. //如果参数不为空,则整合到一起
  74. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导出动态设置mainId
  75. if (params) {
  76. Object.keys(params).map((k) => {
  77. let temp = (params as object)[k];
  78. if (temp) {
  79. paramsForm[k] = unref(temp);
  80. }
  81. });
  82. }
  83. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导出动态设置mainId
  84. if (selectedRowKeys.value && selectedRowKeys.value.length > 0) {
  85. paramsForm['selections'] = selectedRowKeys.value.join(',');
  86. }
  87. return handleExportXls(title as string, realUrl, filterObj(paramsForm));
  88. //update-end---author:wangshuai ---date:20220411 for:导出新增自定义参数--------------
  89. } else {
  90. $message.createMessage.warn('没有传递 exportConfig.url 参数');
  91. return Promise.reject();
  92. }
  93. }
  94. // 导入 excel
  95. function onImportXls(file) {
  96. let { url, success } = options?.importConfig ?? {};
  97. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  98. let realUrl = typeof url === 'function' ? url() : url;
  99. if (realUrl) {
  100. return handleImportXls(file, realUrl, success || reload);
  101. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  102. } else {
  103. $message.createMessage.warn('没有传递 importConfig.url 参数');
  104. return Promise.reject();
  105. }
  106. }
  107. /**
  108. * 通用请求处理方法,可自动刷新表格,自动清空选择
  109. * @param api 请求api
  110. * @param options 是否显示确认框
  111. */
  112. function doRequest(api: () => Promise<any>, options?: IDoRequestOptions) {
  113. return new Promise((resolve, reject) => {
  114. const execute = async () => {
  115. try {
  116. setLoading(true);
  117. const res = await api();
  118. if (options?.reload ?? true) {
  119. reload();
  120. }
  121. if (options?.clearSelection ?? true) {
  122. selectedRowKeys.value = [];
  123. }
  124. resolve(res);
  125. } catch (e) {
  126. reject(e);
  127. } finally {
  128. setLoading(false);
  129. }
  130. };
  131. if (options?.confirm ?? true) {
  132. $message.createConfirm({
  133. iconType: 'warning',
  134. title: '删除',
  135. content: '确定要删除吗?',
  136. onOk: () => execute(),
  137. onCancel: () => reject(),
  138. });
  139. } else {
  140. execute();
  141. }
  142. });
  143. }
  144. /** 执行单个删除操作 */
  145. function doDeleteRecord(api: () => Promise<any>) {
  146. return doRequest(api, { confirm: false, clearSelection: false });
  147. }
  148. return {
  149. ...$design,
  150. ...$message,
  151. onExportXls,
  152. onImportXls,
  153. doRequest,
  154. doDeleteRecord,
  155. tableContext,
  156. };
  157. }
  158. // 定义表格所需参数
  159. type TableProps = Partial<DynamicProps<BasicTableProps>>;
  160. type UseTableMethod = TableActionType & {
  161. getForm: () => FormActionType;
  162. };
  163. /**
  164. * useListTable 列表页面标准表格参数
  165. *
  166. * @param tableProps 表格参数
  167. */
  168. export function useListTable(tableProps: TableProps): [
  169. (instance: TableActionType, formInstance: UseTableMethod) => void,
  170. TableActionType & {
  171. getForm: () => FormActionType;
  172. },
  173. {
  174. rowSelection: any;
  175. selectedRows: Ref<Recordable[]>;
  176. selectedRowKeys: Ref<any[]>;
  177. }
  178. ] {
  179. // 自适应列配置
  180. const adaptiveColProps: Partial<ColEx> = {
  181. xs: 24, // <576px
  182. sm: 12, // ≥576px
  183. md: 12, // ≥768px
  184. lg: 8, // ≥992px
  185. xl: 8, // ≥1200px
  186. xxl: 6, // ≥1600px
  187. };
  188. const defaultTableProps: TableProps = {
  189. rowKey: 'id',
  190. // 使用查询条件区域
  191. useSearchForm: true,
  192. // 查询条件区域配置
  193. formConfig: {
  194. // 紧凑模式
  195. compact: true,
  196. // label默认宽度
  197. labelWidth: 120,
  198. // 按下回车后自动提交
  199. autoSubmitOnEnter: true,
  200. // 默认 row 配置
  201. rowProps: { gutter: 8 },
  202. // 默认 col 配置
  203. baseColProps: {
  204. ...adaptiveColProps,
  205. },
  206. labelCol: {
  207. xs: 24,
  208. sm: 8,
  209. md: 6,
  210. lg: 8,
  211. xl: 6,
  212. xxl: 6,
  213. },
  214. wrapperCol: {},
  215. // 是否显示 展开/收起 按钮
  216. showAdvancedButton: true,
  217. // 超过指定列数默认折叠
  218. autoAdvancedCol: 3,
  219. // 操作按钮配置
  220. actionColOptions: {
  221. ...adaptiveColProps,
  222. style: { textAlign: 'left' },
  223. },
  224. },
  225. // 斑马纹
  226. striped: true,
  227. // 是否可以自适应高度
  228. canResize: true,
  229. // 表格最小高度
  230. minHeight: 500,
  231. // 点击行选中
  232. clickToRowSelect: false,
  233. // 是否显示边框
  234. bordered: true,
  235. // 是否显示序号列
  236. showIndexColumn: false,
  237. // 显示表格设置
  238. showTableSetting: true,
  239. // 表格设置
  240. tableSetting: {
  241. fullScreen: true,
  242. },
  243. // 是否显示操作列
  244. showActionColumn: true,
  245. // 操作列
  246. actionColumn: {
  247. width: 120,
  248. title: '操作',
  249. //是否锁定操作列取值 right ,left,false
  250. fixed: false,
  251. dataIndex: 'action',
  252. slots: { customRender: 'action' },
  253. },
  254. };
  255. // 合并用户个性化配置
  256. if (tableProps) {
  257. // merge 方法可深度合并对象
  258. merge(defaultTableProps, tableProps);
  259. }
  260. // 发送请求之前调用的方法
  261. function beforeFetch(params) {
  262. // 默认以 createTime 降序排序
  263. return Object.assign({ column: 'createTime', order: 'desc' }, params);
  264. }
  265. // 合并方法
  266. Object.assign(defaultTableProps, { beforeFetch });
  267. if (typeof tableProps.beforeFetch === 'function') {
  268. defaultTableProps.beforeFetch = function (params) {
  269. params = beforeFetch(params);
  270. // @ts-ignore
  271. tableProps.beforeFetch(params);
  272. return params;
  273. };
  274. }
  275. // 当前选择的行
  276. const selectedRowKeys = ref<any[]>([]);
  277. // 选择的行记录
  278. const selectedRows = ref<Recordable[]>([]);
  279. // 表格选择列配置
  280. const rowSelection: any = tableProps?.rowSelection ?? {};
  281. const defaultRowSelection = reactive({
  282. ...rowSelection,
  283. type: rowSelection.type ?? 'checkbox',
  284. // 选择列宽度,默认 50
  285. columnWidth: rowSelection.columnWidth ?? 50,
  286. selectedRows: selectedRows,
  287. selectedRowKeys: selectedRowKeys,
  288. onChange(...args) {
  289. selectedRowKeys.value = args[0];
  290. selectedRows.value = args[1];
  291. if (typeof rowSelection.onChange === 'function') {
  292. rowSelection.onChange(...args);
  293. }
  294. },
  295. });
  296. delete defaultTableProps.rowSelection;
  297. return [
  298. ...useTable(defaultTableProps),
  299. {
  300. selectedRows,
  301. selectedRowKeys,
  302. rowSelection: defaultRowSelection,
  303. },
  304. ];
  305. }