use-vxe-grid.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <script lang="ts" setup>
  2. import type { VbenFormProps } from '@vben-core/form-ui';
  3. import type {
  4. VxeGridDefines,
  5. VxeGridInstance,
  6. VxeGridListeners,
  7. VxeGridPropTypes,
  8. VxeGridProps as VxeTableGridProps,
  9. } from 'vxe-table';
  10. import type { ExtendedVxeGridApi, VxeGridProps } from './types';
  11. import {
  12. computed,
  13. nextTick,
  14. onMounted,
  15. onUnmounted,
  16. toRaw,
  17. useSlots,
  18. useTemplateRef,
  19. watch,
  20. } from 'vue';
  21. import { usePriorityValues } from '@vben/hooks';
  22. import { EmptyIcon } from '@vben/icons';
  23. import { $t } from '@vben/locales';
  24. import { usePreferences } from '@vben/preferences';
  25. import { cloneDeep, cn, mergeWithArrayOverride } from '@vben/utils';
  26. import { VbenHelpTooltip, VbenLoading } from '@vben-core/shadcn-ui';
  27. import { VxeGrid, VxeUI } from 'vxe-table';
  28. import { extendProxyOptions } from './extends';
  29. import { useTableForm } from './init';
  30. import 'vxe-table/styles/cssvar.scss';
  31. import 'vxe-pc-ui/styles/cssvar.scss';
  32. import './style.css';
  33. interface Props extends VxeGridProps {
  34. api: ExtendedVxeGridApi;
  35. }
  36. const props = withDefaults(defineProps<Props>(), {});
  37. const FORM_SLOT_PREFIX = 'form-';
  38. const TOOLBAR_ACTIONS = 'toolbar-actions';
  39. const TOOLBAR_TOOLS = 'toolbar-tools';
  40. const gridRef = useTemplateRef<VxeGridInstance>('gridRef');
  41. const state = props.api?.useStore?.();
  42. const {
  43. gridOptions,
  44. class: className,
  45. gridClass,
  46. gridEvents,
  47. formOptions,
  48. tableTitle,
  49. tableTitleHelp,
  50. showSearchForm,
  51. } = usePriorityValues(props, state);
  52. const { isMobile } = usePreferences();
  53. const slots = useSlots();
  54. const [Form, formApi] = useTableForm({
  55. handleSubmit: async () => {
  56. const formValues = formApi.form.values;
  57. formApi.setLatestSubmissionValues(toRaw(formValues));
  58. props.api.reload(formValues);
  59. },
  60. handleReset: async () => {
  61. await formApi.resetForm();
  62. const formValues = formApi.form.values;
  63. formApi.setLatestSubmissionValues(formValues);
  64. props.api.reload(formValues);
  65. },
  66. commonConfig: {
  67. componentProps: {
  68. class: 'w-full',
  69. },
  70. },
  71. showCollapseButton: true,
  72. submitButtonOptions: {
  73. content: $t('common.query'),
  74. },
  75. wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
  76. });
  77. const showTableTitle = computed(() => {
  78. return !!slots.tableTitle?.() || tableTitle.value;
  79. });
  80. const showToolbar = computed(() => {
  81. return (
  82. !!slots[TOOLBAR_ACTIONS]?.() ||
  83. !!slots[TOOLBAR_TOOLS]?.() ||
  84. showTableTitle.value
  85. );
  86. });
  87. const toolbarOptions = computed(() => {
  88. const slotActions = slots[TOOLBAR_ACTIONS]?.();
  89. const slotTools = slots[TOOLBAR_TOOLS]?.();
  90. const toolbarConfig: VxeGridPropTypes.ToolbarConfig = {
  91. tools:
  92. gridOptions.value?.toolbarConfig?.search && !!formOptions.value
  93. ? [
  94. {
  95. code: 'search',
  96. icon: 'vxe-icon--search',
  97. circle: true,
  98. status: showSearchForm.value ? 'primary' : undefined,
  99. title: $t('common.search'),
  100. },
  101. ]
  102. : [],
  103. };
  104. if (!showToolbar.value) {
  105. return { toolbarConfig };
  106. }
  107. // if (gridOptions.value?.toolbarConfig?.search) {
  108. // }
  109. // 强制使用固定的toolbar配置,不允许用户自定义
  110. // 减少配置的复杂度,以及后续维护的成本
  111. toolbarConfig.slots = {
  112. ...(slotActions || showTableTitle.value
  113. ? { buttons: TOOLBAR_ACTIONS }
  114. : {}),
  115. ...(slotTools ? { tools: TOOLBAR_TOOLS } : {}),
  116. };
  117. return { toolbarConfig };
  118. });
  119. const options = computed(() => {
  120. const globalGridConfig = VxeUI?.getConfig()?.grid ?? {};
  121. const mergedOptions: VxeTableGridProps = cloneDeep(
  122. mergeWithArrayOverride(
  123. {},
  124. toolbarOptions.value,
  125. toRaw(gridOptions.value),
  126. globalGridConfig,
  127. ),
  128. );
  129. if (mergedOptions.proxyConfig) {
  130. const { ajax } = mergedOptions.proxyConfig;
  131. mergedOptions.proxyConfig.enabled = !!ajax;
  132. // 不自动加载数据, 由组件控制
  133. mergedOptions.proxyConfig.autoLoad = false;
  134. }
  135. if (mergedOptions.pagerConfig) {
  136. const mobileLayouts = [
  137. 'PrevJump',
  138. 'PrevPage',
  139. 'Number',
  140. 'NextPage',
  141. 'NextJump',
  142. ] as any;
  143. const layouts = [
  144. 'Total',
  145. 'Sizes',
  146. 'Home',
  147. ...mobileLayouts,
  148. 'End',
  149. ] as readonly string[];
  150. mergedOptions.pagerConfig = mergeWithArrayOverride(
  151. {},
  152. mergedOptions.pagerConfig,
  153. {
  154. pageSize: 20,
  155. background: true,
  156. pageSizes: [10, 20, 30, 50, 100, 200],
  157. className: 'mt-2 w-full',
  158. layouts: isMobile.value ? mobileLayouts : layouts,
  159. size: 'mini' as const,
  160. },
  161. );
  162. }
  163. if (mergedOptions.formConfig) {
  164. mergedOptions.formConfig.enabled = false;
  165. }
  166. return mergedOptions;
  167. });
  168. function onToolbarToolClick(event: VxeGridDefines.ToolbarToolClickEventParams) {
  169. if (event.code === 'search') {
  170. props.api?.toggleSearchForm?.();
  171. }
  172. (
  173. gridEvents.value?.toolbarToolClick as VxeGridListeners['toolbarToolClick']
  174. )?.(event);
  175. }
  176. const events = computed(() => {
  177. return {
  178. ...gridEvents.value,
  179. toolbarToolClick: onToolbarToolClick,
  180. };
  181. });
  182. const delegatedSlots = computed(() => {
  183. const resultSlots: string[] = [];
  184. for (const key of Object.keys(slots)) {
  185. if (!['empty', 'form', 'loading', TOOLBAR_ACTIONS].includes(key)) {
  186. resultSlots.push(key);
  187. }
  188. }
  189. return resultSlots;
  190. });
  191. const delegatedFormSlots = computed(() => {
  192. const resultSlots: string[] = [];
  193. for (const key of Object.keys(slots)) {
  194. if (key.startsWith(FORM_SLOT_PREFIX)) {
  195. resultSlots.push(key);
  196. }
  197. }
  198. return resultSlots.map((key) => key.replace(FORM_SLOT_PREFIX, ''));
  199. });
  200. async function init() {
  201. await nextTick();
  202. const globalGridConfig = VxeUI?.getConfig()?.grid ?? {};
  203. const defaultGridOptions: VxeTableGridProps = mergeWithArrayOverride(
  204. {},
  205. toRaw(gridOptions.value),
  206. toRaw(globalGridConfig),
  207. );
  208. // 内部主动加载数据,防止form的默认值影响
  209. const autoLoad = defaultGridOptions.proxyConfig?.autoLoad;
  210. const enableProxyConfig = options.value.proxyConfig?.enabled;
  211. if (enableProxyConfig && autoLoad) {
  212. props.api.reload(formApi.form?.values ?? {});
  213. }
  214. // form 由 vben-form代替,所以不适配formConfig,这里给出警告
  215. const formConfig = gridOptions.value?.formConfig;
  216. // 处理某个页面加载多个Table时,第2个之后的Table初始化报出警告
  217. // 因为第一次初始化之后会把defaultGridOptions和gridOptions合并后缓存进State
  218. if (formConfig && formConfig.enabled) {
  219. console.warn(
  220. '[Vben Vxe Table]: The formConfig in the grid is not supported, please use the `formOptions` props',
  221. );
  222. }
  223. props.api?.setState?.({ gridOptions: defaultGridOptions });
  224. // form 由 vben-form 代替,所以需要保证query相关事件可以拿到参数
  225. extendProxyOptions(props.api, defaultGridOptions, () =>
  226. formApi.getLatestSubmissionValues(),
  227. );
  228. }
  229. // formOptions支持响应式
  230. watch(
  231. formOptions,
  232. () => {
  233. formApi.setState((prev) => {
  234. const finalFormOptions: VbenFormProps = mergeWithArrayOverride(
  235. {},
  236. formOptions.value,
  237. prev,
  238. );
  239. return {
  240. ...finalFormOptions,
  241. collapseTriggerResize: !!finalFormOptions.showCollapseButton,
  242. };
  243. });
  244. },
  245. {
  246. immediate: true,
  247. },
  248. );
  249. onMounted(() => {
  250. props.api?.mount?.(gridRef.value, formApi);
  251. init();
  252. });
  253. onUnmounted(() => {
  254. formApi?.unmount?.();
  255. props.api?.unmount?.();
  256. });
  257. </script>
  258. <template>
  259. <div :class="cn('bg-card h-full rounded-md', className)">
  260. <VxeGrid
  261. ref="gridRef"
  262. :class="
  263. cn(
  264. 'p-2 pt-0',
  265. {
  266. 'pt-0': showToolbar && !formOptions,
  267. },
  268. gridClass,
  269. )
  270. "
  271. v-bind="options"
  272. v-on="events"
  273. >
  274. <!-- 左侧操作区域或者title -->
  275. <template v-if="showToolbar" #toolbar-actions="slotProps">
  276. <slot v-if="showTableTitle" name="table-title">
  277. <div class="mr-1 pl-1 text-[1rem]">
  278. {{ tableTitle }}
  279. <VbenHelpTooltip v-if="tableTitleHelp" trigger-class="pb-1">
  280. {{ tableTitleHelp }}
  281. </VbenHelpTooltip>
  282. </div>
  283. </slot>
  284. <slot name="toolbar-actions" v-bind="slotProps"> </slot>
  285. </template>
  286. <!-- 继承默认的slot -->
  287. <template
  288. v-for="slotName in delegatedSlots"
  289. :key="slotName"
  290. #[slotName]="slotProps"
  291. >
  292. <slot :name="slotName" v-bind="slotProps"></slot>
  293. </template>
  294. <!-- form表单 -->
  295. <template #form>
  296. <div
  297. v-if="formOptions"
  298. v-show="showSearchForm !== false"
  299. class="relative rounded py-3 pb-4"
  300. >
  301. <slot name="form">
  302. <Form>
  303. <template
  304. v-for="slotName in delegatedFormSlots"
  305. :key="slotName"
  306. #[slotName]="slotProps"
  307. >
  308. <slot
  309. :name="`${FORM_SLOT_PREFIX}${slotName}`"
  310. v-bind="slotProps"
  311. ></slot>
  312. </template>
  313. <template #reset-before="slotProps">
  314. <slot name="reset-before" v-bind="slotProps"></slot>
  315. </template>
  316. <template #submit-before="slotProps">
  317. <slot name="submit-before" v-bind="slotProps"></slot>
  318. </template>
  319. <template #expand-before="slotProps">
  320. <slot name="expand-before" v-bind="slotProps"></slot>
  321. </template>
  322. <template #expand-after="slotProps">
  323. <slot name="expand-after" v-bind="slotProps"></slot>
  324. </template>
  325. </Form>
  326. </slot>
  327. <div
  328. class="bg-background-deep z-100 absolute -left-2 bottom-1 h-2 w-[calc(100%+1rem)] overflow-hidden md:bottom-2 md:h-3"
  329. ></div>
  330. </div>
  331. </template>
  332. <!-- loading -->
  333. <template #loading>
  334. <slot name="loading">
  335. <VbenLoading :spinning="true" />
  336. </slot>
  337. </template>
  338. <!-- 统一控状态 -->
  339. <template #empty>
  340. <slot name="empty">
  341. <EmptyIcon class="mx-auto" />
  342. <div class="mt-2">{{ $t('common.noData') }}</div>
  343. </slot>
  344. </template>
  345. </VxeGrid>
  346. </div>
  347. </template>