usePage.ts 1.7 KB

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