use-vxe-grid.vue 11 KB

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