index.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { shallowRef, defineAsyncComponent, Component } from 'vue'
  2. import { useRoute } from 'vue-router'
  3. import { findTreeNodeById } from '@/filters'
  4. import { AuthType } from '@/constants/menu'
  5. import { useRouterStore } from '@/stores'
  6. import { OperationOptions } from './types'
  7. export function useOperation<T>({ code, onClose }: OperationOptions = {}) {
  8. const route = useRoute()
  9. const routerStore = useRouterStore()
  10. const routeName = code ?? String(route.name)
  11. const menus = findTreeNodeById(routerStore.userRoutes, routeName, { id: 'resourceCode' })
  12. const buttons: Model.MenusRsp[] = []
  13. const componentMap = new Map<string, Component>()
  14. const componentId = shallowRef<string>()
  15. const record = shallowRef<T>()
  16. menus?.children?.forEach((item) => {
  17. if (item.authType === AuthType.Operate && item.show && item.component) {
  18. const componentString = item.component.replace(/^\/+/, '') // 过滤字符串前面所有 '/' 字符
  19. const componentPath = componentString.replace(/\.\w+$/, '') // 过滤后缀名,为了让 import 加入 .vue ,不然会有警告提示...
  20. const asyncComponent = defineAsyncComponent({
  21. loader: () => import('/' + process.env.VUE_APP_ROOT + componentPath + '.vue'),
  22. })
  23. componentMap.set(item.resourceCode, asyncComponent)
  24. buttons.push(item)
  25. }
  26. })
  27. // 获取按钮组
  28. const getActionButtons = (filtered?: string[], reverse?: boolean) => {
  29. if (filtered?.length) {
  30. return buttons.filter((item) => filtered.includes(item.resourceCode) === !reverse)
  31. }
  32. return buttons
  33. }
  34. // 打开组件
  35. const openComponent = (id: string, row?: T) => {
  36. record.value = row
  37. componentId.value = id
  38. }
  39. // 关闭组件
  40. const closeComponent = (triggerEvent: boolean) => {
  41. if (triggerEvent && onClose) {
  42. onClose(componentId.value ?? '')
  43. }
  44. componentId.value = undefined
  45. }
  46. return {
  47. componentMap,
  48. componentId,
  49. record,
  50. openComponent,
  51. closeComponent,
  52. getActionButtons
  53. }
  54. }