usePage.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import type { RouteLocationRaw, Router } from 'vue-router';
  2. import { PageEnum } from '@/enums/pageEnum';
  3. import { unref } from 'vue';
  4. import { useRouter } from 'vue-router';
  5. import { REDIRECT_NAME } from '@/router/constant';
  6. import { isHttpUrl } from '@/utils/is';
  7. import { openWindow } from '@/utils';
  8. export type PathAsPageEnum<T> = T extends { path: string } ? T & { path: PageEnum } : T;
  9. export type RouteLocationRawEx = PathAsPageEnum<RouteLocationRaw>;
  10. function handleError(e: Error) {
  11. console.error(e);
  12. }
  13. /**
  14. * page switch
  15. */
  16. export function useGo(_router?: Router) {
  17. const { push, replace } = _router || useRouter();
  18. function go(opt: RouteLocationRawEx = PageEnum.BASE_HOME, isReplace = false) {
  19. if (!opt) {
  20. return;
  21. }
  22. let path = unref(opt) as string;
  23. if (path[0] === '/') {
  24. path = path.slice(1);
  25. }
  26. if (isHttpUrl(path)) {
  27. return openWindow(path);
  28. }
  29. isReplace ? replace(opt).catch(handleError) : push(opt).catch(handleError);
  30. }
  31. return go;
  32. }
  33. /**
  34. * @description: redo current page
  35. */
  36. export const useRedo = (_router?: Router) => {
  37. const { replace, currentRoute } = _router || useRouter();
  38. const { query, params = {}, name, fullPath } = unref(currentRoute.value);
  39. function redo(): Promise<boolean> {
  40. return new Promise((resolve) => {
  41. if (name === REDIRECT_NAME) {
  42. resolve(false);
  43. return;
  44. }
  45. if (name && Object.keys(params).length > 0) {
  46. params['_origin_params'] = JSON.stringify(params ?? {});
  47. params['_redirect_type'] = 'name';
  48. params['path'] = String(name);
  49. } else {
  50. params['_redirect_type'] = 'path';
  51. params['path'] = fullPath;
  52. }
  53. replace({ name: REDIRECT_NAME, params, query }).then(() => resolve(true));
  54. });
  55. }
  56. return redo;
  57. };