vxe-table.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
  2. import type { Recordable } from '@vben/types';
  3. import type { ComponentPropsMap, ComponentType } from './component';
  4. import { h } from 'vue';
  5. import { IconifyIcon } from '@vben/icons';
  6. import { $te } from '@vben/locales';
  7. import {
  8. setupVbenVxeTable,
  9. useVbenVxeGrid as useGrid,
  10. } from '@vben/plugins/vxe-table';
  11. import { get, isFunction, isString } from '@vben/utils';
  12. import { objectOmit } from '@vueuse/core';
  13. import { Button, Image, Popconfirm, Switch, Tag } from 'ant-design-vue';
  14. import { $t } from '#/locales';
  15. setupVbenVxeTable({
  16. configVxeTable: (vxeUI) => {
  17. vxeUI.setConfig({
  18. grid: {
  19. align: 'center',
  20. border: false,
  21. columnConfig: {
  22. resizable: true,
  23. },
  24. formConfig: {
  25. // 全局禁用vxe-table的表单配置,使用formOptions
  26. enabled: false,
  27. },
  28. minHeight: 180,
  29. proxyConfig: {
  30. autoLoad: true,
  31. response: {
  32. result: 'items',
  33. total: 'total',
  34. list: '',
  35. },
  36. showActiveMsg: true,
  37. showResponseMsg: false,
  38. },
  39. round: true,
  40. showOverflow: true,
  41. size: 'small',
  42. } as VxeTableGridOptions,
  43. });
  44. /**
  45. * 解决vxeTable在热更新时可能会出错的问题
  46. */
  47. vxeUI.renderer.forEach((_item, key) => {
  48. if (key.startsWith('Cell')) {
  49. vxeUI.renderer.delete(key);
  50. }
  51. });
  52. // 表格配置项可以用 cellRender: { name: 'CellImage' },
  53. vxeUI.renderer.add('CellImage', {
  54. renderTableDefault(renderOpts, params) {
  55. const { props } = renderOpts;
  56. const { column, row } = params;
  57. return h(Image, { src: row[column.field], ...props });
  58. },
  59. });
  60. // 表格配置项可以用 cellRender: { name: 'CellLink' },
  61. vxeUI.renderer.add('CellLink', {
  62. renderTableDefault(renderOpts) {
  63. const { props } = renderOpts;
  64. return h(
  65. Button,
  66. { size: 'small', type: 'link' },
  67. { default: () => props?.text },
  68. );
  69. },
  70. });
  71. // 单元格渲染: Tag
  72. vxeUI.renderer.add('CellTag', {
  73. renderTableDefault({ options, props }, { column, row }) {
  74. const value = get(row, column.field);
  75. const tagOptions = options ?? [
  76. { color: 'success', label: $t('common.enabled'), value: 1 },
  77. { color: 'error', label: $t('common.disabled'), value: 0 },
  78. ];
  79. const tagItem = tagOptions.find((item) => item.value === value);
  80. return h(
  81. Tag,
  82. {
  83. ...props,
  84. ...objectOmit(tagItem ?? {}, ['label']),
  85. },
  86. { default: () => tagItem?.label ?? value },
  87. );
  88. },
  89. });
  90. vxeUI.renderer.add('CellSwitch', {
  91. renderTableDefault({ attrs, props }, { column, row }) {
  92. const loadingKey = `__loading_${column.field}`;
  93. const finallyProps = {
  94. checkedChildren: $t('common.enabled'),
  95. checkedValue: 1,
  96. unCheckedChildren: $t('common.disabled'),
  97. unCheckedValue: 0,
  98. ...props,
  99. checked: row[column.field],
  100. loading: row[loadingKey] ?? false,
  101. 'onUpdate:checked': onChange,
  102. };
  103. async function onChange(newVal: any) {
  104. row[loadingKey] = true;
  105. try {
  106. const result = await attrs?.beforeChange?.(newVal, row);
  107. if (result !== false) {
  108. row[column.field] = newVal;
  109. }
  110. } finally {
  111. row[loadingKey] = false;
  112. }
  113. }
  114. return h(Switch, finallyProps);
  115. },
  116. });
  117. /**
  118. * 注册表格的操作按钮渲染器
  119. */
  120. vxeUI.renderer.add('CellOperation', {
  121. renderTableDefault({ attrs, options, props }, { column, row }) {
  122. const defaultProps = { size: 'small', type: 'link', ...props };
  123. let align: string;
  124. switch (column.align) {
  125. case 'center': {
  126. align = 'center';
  127. break;
  128. }
  129. case 'left': {
  130. align = 'start';
  131. break;
  132. }
  133. default: {
  134. align = 'end';
  135. break;
  136. }
  137. }
  138. const presets: Recordable<Recordable<any>> = {
  139. delete: {
  140. danger: true,
  141. text: $t('common.delete'),
  142. },
  143. edit: {
  144. text: $t('common.edit'),
  145. },
  146. };
  147. const operations: Array<Recordable<any>> = (
  148. options || ['edit', 'delete']
  149. )
  150. .map((opt) => {
  151. if (isString(opt)) {
  152. return presets[opt]
  153. ? { code: opt, ...presets[opt], ...defaultProps }
  154. : {
  155. code: opt,
  156. text: $te(`common.${opt}`) ? $t(`common.${opt}`) : opt,
  157. ...defaultProps,
  158. };
  159. } else {
  160. return { ...defaultProps, ...presets[opt.code], ...opt };
  161. }
  162. })
  163. .map((opt) => {
  164. const optBtn: Recordable<any> = {};
  165. Object.keys(opt).forEach((key) => {
  166. optBtn[key] = isFunction(opt[key]) ? opt[key](row) : opt[key];
  167. });
  168. return optBtn;
  169. })
  170. .filter((opt) => opt.show !== false);
  171. function renderBtn(opt: Recordable<any>, listen = true) {
  172. return h(
  173. Button,
  174. {
  175. ...props,
  176. ...opt,
  177. icon: undefined,
  178. onClick: listen
  179. ? () =>
  180. attrs?.onClick?.({
  181. code: opt.code,
  182. row,
  183. })
  184. : undefined,
  185. },
  186. {
  187. default: () => {
  188. const content = [];
  189. if (opt.icon) {
  190. content.push(
  191. h(IconifyIcon, { class: 'size-5', icon: opt.icon }),
  192. );
  193. }
  194. content.push(opt.text);
  195. return content;
  196. },
  197. },
  198. );
  199. }
  200. function renderConfirm(opt: Recordable<any>) {
  201. let viewportWrapper: HTMLElement | null = null;
  202. return h(
  203. Popconfirm,
  204. {
  205. /**
  206. * 当popconfirm用在固定列中时,将固定列作为弹窗的容器时可能会因为固定列较窄而无法容纳弹窗
  207. * 将表格主体区域作为弹窗容器时又会因为固定列的层级较高而遮挡弹窗
  208. * 将body或者表格视口区域作为弹窗容器时又会导致弹窗无法跟随表格滚动。
  209. * 鉴于以上各种情况,一种折中的解决方案是弹出层展示时,禁止操作表格的滚动条。
  210. * 这样既解决了弹窗的遮挡问题,又不至于让弹窗随着表格的滚动而跑出视口区域。
  211. */
  212. getPopupContainer(el) {
  213. viewportWrapper = el.closest('.vxe-table--viewport-wrapper');
  214. return document.body;
  215. },
  216. placement: 'topLeft',
  217. title: $t('ui.actionTitle.delete', [attrs?.nameTitle || '']),
  218. ...props,
  219. ...opt,
  220. icon: undefined,
  221. onOpenChange: (open: boolean) => {
  222. // 当弹窗打开时,禁止表格的滚动
  223. if (open) {
  224. viewportWrapper?.style.setProperty('pointer-events', 'none');
  225. } else {
  226. viewportWrapper?.style.removeProperty('pointer-events');
  227. }
  228. },
  229. onConfirm: () => {
  230. attrs?.onClick?.({
  231. code: opt.code,
  232. row,
  233. });
  234. },
  235. },
  236. {
  237. default: () => renderBtn({ ...opt }, false),
  238. description: () =>
  239. h(
  240. 'div',
  241. { class: 'truncate' },
  242. $t('ui.actionMessage.deleteConfirm', [
  243. row[attrs?.nameField || 'name'],
  244. ]),
  245. ),
  246. },
  247. );
  248. }
  249. const btns = operations.map((opt) =>
  250. opt.code === 'delete' ? renderConfirm(opt) : renderBtn(opt),
  251. );
  252. return h(
  253. 'div',
  254. {
  255. class: 'flex table-operations',
  256. style: { justifyContent: align },
  257. },
  258. btns,
  259. );
  260. },
  261. });
  262. // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化
  263. // vxeUI.formats.add
  264. },
  265. });
  266. export const useVbenVxeGrid = <T extends Record<string, any>>(
  267. ...rest: Parameters<typeof useGrid<T, ComponentType, ComponentPropsMap>>
  268. ) => useGrid<T, ComponentType, ComponentPropsMap>(...rest);
  269. export type OnActionClickParams<T = Recordable<any>> = {
  270. code: string;
  271. row: T;
  272. };
  273. export type OnActionClickFn<T = Recordable<any>> = (
  274. params: OnActionClickParams<T>,
  275. ) => void;
  276. export type * from '@vben/plugins/vxe-table';