use-vxe-grid.vue 12 KB

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