useRouter.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // useRouter.ts
  2. export default function useRouter() {
  3. type RouteOptions = string | { path: string; query?: Record<string, any> };
  4. const normalizeUrl = (to: RouteOptions) => {
  5. if (typeof to === 'string') return to;
  6. if (typeof to === 'object' && to.path) {
  7. let url = to.path;
  8. if (to.query && Object.keys(to.query).length) {
  9. const queryStr = Object.keys(to.query)
  10. .map(key => `${key}=${encodeURIComponent(to.query![key])}`)
  11. .join('&');
  12. url += `?${queryStr}`;
  13. }
  14. // console.log(url, 'urlurlurl');
  15. return url;
  16. }
  17. throw new Error('[useRouter] Invalid route: ' + JSON.stringify(to));
  18. };
  19. const push = (to: RouteOptions) => {
  20. const url = normalizeUrl(to);
  21. uni.navigateTo({ url });
  22. };
  23. const replace = (to: RouteOptions) => {
  24. const url = normalizeUrl(to);
  25. uni.redirectTo({ url });
  26. };
  27. const switchTo = (to: RouteOptions) => {
  28. const url = normalizeUrl(to);
  29. uni.switchTab({ url });
  30. };
  31. const reLaunch = (to: RouteOptions) => {
  32. const url = normalizeUrl(to);
  33. uni.reLaunch({ url });
  34. };
  35. const back = (delta: number = 1) => {
  36. uni.navigateBack({ delta });
  37. };
  38. return { push, replace, switchTo, reLaunch, back };
  39. }