usePage.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. export type RouteLocationRawEx = Omit<RouteLocationRaw, 'path'> & { path: PageEnum };
  7. function handleError(e: Error) {
  8. console.error(e);
  9. }
  10. // page switch
  11. export function useGo(_router?: Router) {
  12. let router;
  13. if (!_router) {
  14. router = useRouter();
  15. }
  16. const { push, replace } = _router || router;
  17. function go(opt: PageEnum | RouteLocationRawEx | string = PageEnum.BASE_HOME, isReplace = false) {
  18. if (!opt) {
  19. return;
  20. }
  21. if (isString(opt)) {
  22. isReplace ? replace(opt).catch(handleError) : push(opt).catch(handleError);
  23. } else {
  24. const o = opt as RouteLocationRaw;
  25. isReplace ? replace(o).catch(handleError) : push(o).catch(handleError);
  26. }
  27. }
  28. return go;
  29. }
  30. /**
  31. * @description: redo current page
  32. */
  33. export const useRedo = (_router?: Router) => {
  34. let router;
  35. if (!_router) {
  36. router = useRouter();
  37. }
  38. const { push, currentRoute } = _router || router;
  39. const { query, params } = currentRoute.value;
  40. function redo(): Promise<boolean> {
  41. return new Promise((resolve) => {
  42. push({
  43. path: '/redirect' + unref(currentRoute).fullPath,
  44. query,
  45. params,
  46. }).then(() => resolve(true));
  47. });
  48. }
  49. return redo;
  50. };