use-vxe-grid.vue 13 KB

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