use-vxe-grid.vue 9.1 KB

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