router.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // 对象转为路径参数
  2. export const objToUrlParams = (obj) => {
  3. if (typeof obj === "string") return obj;
  4. let result = "?";
  5. for (const element in obj) {
  6. result += `${element}=${obj[element]}&`;
  7. }
  8. return result.substring(0, result.length - 1);
  9. };
  10. // 将字符串转为对象
  11. export const urlParamsToObj = (url) => {
  12. const params = url.split("?")[1];
  13. if (!params) return {};
  14. const paramsArr = params.split("&");
  15. const result = {};
  16. paramsArr.forEach((item) => {
  17. const [key, value] = item.split("=");
  18. result[key] = value;
  19. });
  20. return result;
  21. };
  22. // 参数归一化路由参数
  23. const normalizeParams = (url, options) => {
  24. let normalizeOptions = {
  25. url: "",
  26. };
  27. if (typeof url === "string") {
  28. normalizeOptions = {
  29. url,
  30. ...options,
  31. };
  32. } else {
  33. normalizeOptions = url;
  34. }
  35. const params = normalizeOptions.params || {};
  36. normalizeOptions.url += objToUrlParams(params);
  37. delete normalizeOptions.params;
  38. return normalizeOptions;
  39. };
  40. // 路由映射表
  41. export const router = {
  42. /**
  43. * 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。
  44. */
  45. push(url, options) {
  46. const normalizeOptions = normalizeParams(url, options);
  47. uni.navigateTo(normalizeOptions);
  48. },
  49. /**
  50. * 关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
  51. */
  52. redirectTo(url, options) {
  53. const normalizeOptions = normalizeParams(url, options);
  54. uni.redirectTo(normalizeOptions);
  55. },
  56. /**
  57. * 关闭所有页面,打开到应用内的某个页面。
  58. */
  59. reLaunch(url, options) {
  60. const normalizeOptions = normalizeParams(url, options);
  61. uni.reLaunch(normalizeOptions);
  62. },
  63. /**
  64. * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
  65. */
  66. switchTab(url, options) {
  67. const normalizeOptions = normalizeParams(url, options);
  68. uni.switchTab(normalizeOptions);
  69. },
  70. /**
  71. * 关闭当前页面,返回上一页面或多级页面。
  72. */
  73. back() {
  74. const route = getRoute().routeList;
  75. if (route.length > 1) {
  76. uni.navigateBack();
  77. return;
  78. }
  79. const { redirected, ...params } = route[0].params;
  80. if (redirected) {
  81. this.reLaunch({
  82. url: redirected,
  83. params,
  84. });
  85. }
  86. },
  87. };
  88. // 获取当前路由参数
  89. export const getRoute = () => {
  90. const pages = getCurrentPages();
  91. const routeList = pages.map((item, index) => {
  92. return {
  93. params: item.options,
  94. path: item.route,
  95. index,
  96. };
  97. });
  98. return {
  99. routeList,
  100. };
  101. };