use-vxe-grid.vue 9.2 KB

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