use-vxe-grid.vue 14 KB

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