vxe-table.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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, resolveDirective, withDirectives } 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. minHeight: 180,
  26. formConfig: {
  27. // 全局禁用vxe-table的表单配置,使用formOptions
  28. enabled: false,
  29. },
  30. proxyConfig: {
  31. autoLoad: true,
  32. response: {
  33. result: 'items',
  34. total: 'total',
  35. list: 'items',
  36. },
  37. showActiveMsg: true,
  38. showResponseMsg: false,
  39. },
  40. round: true,
  41. showOverflow: true,
  42. size: 'small',
  43. } as VxeTableGridOptions,
  44. });
  45. if (import.meta.env.DEV) {
  46. // 解决vxeTable在热更新时可能会出错的问题
  47. vxeUI.renderer.forEach((_item, key) => {
  48. if (key.startsWith('Cell')) {
  49. vxeUI.renderer.delete(key);
  50. }
  51. });
  52. }
  53. // 表格配置项可以用 cellRender: { name: 'CellImage' },
  54. vxeUI.renderer.add('CellImage', {
  55. renderTableDefault(_renderOpts, params) {
  56. const { column, row } = params;
  57. return h(Image, { src: row[column.field] });
  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 { accessRole, accessCode, _props } = props ?? {};
  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. const access = resolveDirective('access');
  116. const modifiers = { disabled: true };
  117. return withDirectives(
  118. h(Switch, finallyProps),
  119. [
  120. accessCode && [access, accessCode, 'code', modifiers],
  121. accessRole && [access, accessRole, 'role', modifiers],
  122. ].filter(Boolean),
  123. );
  124. },
  125. });
  126. /**
  127. * 注册表格的操作按钮渲染器
  128. */
  129. vxeUI.renderer.add('CellOperation', {
  130. renderTableDefault({ attrs, options, props }, { column, row }) {
  131. const defaultProps = { size: 'small', type: 'link', ...props };
  132. let align = 'end';
  133. switch (column.align) {
  134. case 'center': {
  135. align = 'center';
  136. break;
  137. }
  138. case 'left': {
  139. align = 'start';
  140. break;
  141. }
  142. default: {
  143. align = 'end';
  144. break;
  145. }
  146. }
  147. const presets: Recordable<Recordable<any>> = {
  148. delete: {
  149. danger: true,
  150. text: $t('common.delete'),
  151. },
  152. edit: {
  153. text: $t('common.edit'),
  154. },
  155. };
  156. const operations: Array<Recordable<any>> = (
  157. options || ['edit', 'delete']
  158. )
  159. .map((opt) => {
  160. if (isString(opt)) {
  161. return presets[opt]
  162. ? { code: opt, ...presets[opt], ...defaultProps }
  163. : {
  164. code: opt,
  165. text: $te(`common.${opt}`) ? $t(`common.${opt}`) : opt,
  166. ...defaultProps,
  167. };
  168. } else {
  169. return { ...defaultProps, ...presets[opt.code], ...opt };
  170. }
  171. })
  172. .map((opt) => {
  173. const optBtn: Recordable<any> = {};
  174. Object.keys(opt).forEach((key) => {
  175. optBtn[key] = isFunction(opt[key]) ? opt[key](row) : opt[key];
  176. });
  177. return optBtn;
  178. })
  179. .filter((opt) => opt.show !== false);
  180. function renderBtn(opt: Recordable<any>, listen = true) {
  181. return h(
  182. Button,
  183. {
  184. ...props,
  185. ...opt,
  186. icon: undefined,
  187. onClick: listen
  188. ? () =>
  189. attrs?.onClick?.({
  190. code: opt.code,
  191. row,
  192. })
  193. : undefined,
  194. },
  195. {
  196. default: () => {
  197. const content = [];
  198. if (opt.icon) {
  199. content.push(
  200. h(IconifyIcon, { class: 'size-5', icon: opt.icon }),
  201. );
  202. }
  203. content.push(opt.text);
  204. return content;
  205. },
  206. },
  207. );
  208. }
  209. function renderConfirm(opt: Recordable<any>) {
  210. let viewportWrapper: HTMLElement | null = null;
  211. return h(
  212. Popconfirm,
  213. {
  214. /**
  215. * 当popconfirm用在固定列中时,将固定列作为弹窗的容器时可能会因为固定列较窄而无法容纳弹窗
  216. * 将表格主体区域作为弹窗容器时又会因为固定列的层级较高而遮挡弹窗
  217. * 将body或者表格视口区域作为弹窗容器时又会导致弹窗无法跟随表格滚动。
  218. * 鉴于以上各种情况,一种折中的解决方案是弹出层展示时,禁止操作表格的滚动条。
  219. * 这样既解决了弹窗的遮挡问题,又不至于让弹窗随着表格的滚动而跑出视口区域。
  220. */
  221. getPopupContainer(el) {
  222. viewportWrapper = el.closest('.vxe-table--viewport-wrapper');
  223. return document.body;
  224. },
  225. placement: 'topLeft',
  226. title: $t('ui.actionTitle.delete', [attrs?.nameTitle || '']),
  227. ...props,
  228. ...opt,
  229. icon: undefined,
  230. onOpenChange: (open: boolean) => {
  231. // 当弹窗打开时,禁止表格的滚动
  232. if (open) {
  233. viewportWrapper?.style.setProperty('pointer-events', 'none');
  234. } else {
  235. viewportWrapper?.style.removeProperty('pointer-events');
  236. }
  237. },
  238. onConfirm: () => {
  239. attrs?.onClick?.({
  240. code: opt.code,
  241. row,
  242. });
  243. },
  244. },
  245. {
  246. default: () => renderBtn({ ...opt }, false),
  247. description: () =>
  248. h(
  249. 'div',
  250. { class: 'truncate' },
  251. $t('ui.actionMessage.deleteConfirm', [
  252. row[attrs?.nameField || 'name'],
  253. ]),
  254. ),
  255. },
  256. );
  257. }
  258. const btns = operations.map((opt) =>
  259. opt.code === 'delete' ? renderConfirm(opt) : renderBtn(opt),
  260. );
  261. return h(
  262. 'div',
  263. {
  264. class: 'flex table-operations',
  265. style: { justifyContent: align },
  266. },
  267. btns,
  268. );
  269. },
  270. });
  271. // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化
  272. // vxeUI.formats.add
  273. },
  274. useVbenForm,
  275. });
  276. export const useVbenVxeGrid = <T extends Record<string, any>>(
  277. ...rest: Parameters<typeof useGrid<T, ComponentType>>
  278. ) => useGrid<T, ComponentType>(...rest);
  279. export type OnActionClickParams<T = Recordable<any>> = {
  280. code: string;
  281. row: T;
  282. };
  283. export type OnActionClickFn<T = Recordable<any>> = (
  284. params: OnActionClickParams<T>,
  285. ) => void;
  286. export type * from '@vben/plugins/vxe-table';