useRouter.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // useRouter.ts
  2. export default function useRouter() {
  3. type RouteOptions = string | {
  4. path: string;
  5. query?: Record<string, any>;
  6. animationType?: 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' |
  7. 'fade-in' | 'zoom-in' | 'pop-in' | 'none';
  8. animationDuration?: number;
  9. };
  10. const normalizeUrl = (to: RouteOptions) => {
  11. if (typeof to === 'string') return to;
  12. if (typeof to === 'object' && to.path) {
  13. let url = to.path;
  14. if (to.query && Object.keys(to.query).length) {
  15. const queryStr = Object.keys(to.query)
  16. .map(key => `${key}=${encodeURIComponent(to.query![key])}`)
  17. .join('&');
  18. url += `?${queryStr}`;
  19. }
  20. console.log(url, 'urlurlurl');
  21. return url;
  22. }
  23. throw new Error('[useRouter] Invalid route: ' + JSON.stringify(to));
  24. };
  25. // 获取动画配置,默认使用淡入动画
  26. const getAnimationOptions = (to: RouteOptions) => {
  27. // 默认动画:淡入,时长300ms
  28. const defaultAnimation = {
  29. animationType: 'fade-in',
  30. animationDuration: 3000
  31. };
  32. // 如果传入的是字符串,使用默认动画
  33. if (typeof to === 'string') {
  34. return defaultAnimation;
  35. }
  36. // 如果传入的是对象且没有指定动画类型,使用默认动画
  37. if (typeof to === 'object') {
  38. return {
  39. animationType: to.animationType || defaultAnimation.animationType,
  40. animationDuration: to.animationDuration || defaultAnimation.animationDuration
  41. };
  42. }
  43. return defaultAnimation;
  44. };
  45. const push = (to: RouteOptions) => {
  46. const url = normalizeUrl(to);
  47. const animation = getAnimationOptions(to);
  48. uni.navigateTo({
  49. url,
  50. "animationType": "fade-in", // 全局默认动画
  51. "animationDuration": 300 // 全局动画时长
  52. });
  53. };
  54. const replace = (to: RouteOptions) => {
  55. const url = normalizeUrl(to);
  56. const animation = getAnimationOptions(to);
  57. uni.redirectTo({
  58. url,
  59. ...animation
  60. });
  61. };
  62. const switchTo = (to: RouteOptions) => {
  63. const url = normalizeUrl(to);
  64. // switchTab 不支持动画
  65. uni.switchTab({ url });
  66. };
  67. const reLaunch = (to: RouteOptions) => {
  68. const url = normalizeUrl(to);
  69. // reLaunch 不支持动画
  70. uni.reLaunch({ url });
  71. };
  72. const back = (delta: number = 1, options?: { animationType?: string; animationDuration?: number }) => {
  73. if (options) {
  74. uni.navigateBack({
  75. delta,
  76. ...options
  77. });
  78. } else {
  79. uni.navigateBack({ delta })
  80. }
  81. };
  82. return { push, replace, switchTo, reLaunch, back };
  83. }