vxe-table.ts 8.9 KB

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