use-vxe-grid.vue 10 KB

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