redirect.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * 旧页面路径跳转壳工具
  3. *
  4. * 背景:G2 契约/目录中性化把 pages/parent、pages/child 迁到 pages/family,
  5. * home-pages/parent-index.vue、child-index.vue 改名为 family-index.vue、member-index.vue。
  6. * 已发布的小程序版本仍可能跳旧路径,因此旧路径保留一个跳转壳,重定向到新路径。
  7. *
  8. * 规则:
  9. * - 保留原页面的查询参数(memberId 等),避免跳转后丢上下文;
  10. * - 优先 redirectTo(保留页面栈),目标为 tabBar 页时 redirectTo 会失败,回退 reLaunch。
  11. */
  12. function buildQuery(options) {
  13. if (!options) return '';
  14. var keys = Object.keys(options);
  15. if (!keys.length) return '';
  16. var parts = [];
  17. for (var i = 0; i < keys.length; i++) {
  18. var key = keys[i];
  19. var value = options[key];
  20. if (value === undefined || value === null) continue;
  21. parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  22. }
  23. return parts.length ? '?' + parts.join('&') : '';
  24. }
  25. /**
  26. * 跳转到新页面路径
  27. * @param {string} targetPath 新页面路径,如 '/pages/family/appointments'
  28. * @param {object} [options] 查询参数;缺省时自动从当前页面实例读取
  29. */
  30. export function redirectToNewPath(targetPath, options) {
  31. var opts = options;
  32. if (!opts) {
  33. var pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
  34. var current = pages && pages.length ? pages[pages.length - 1] : null;
  35. opts = (current && current.options) || {};
  36. }
  37. var url = targetPath + buildQuery(opts);
  38. uni.redirectTo({
  39. url: url,
  40. fail: function () {
  41. uni.reLaunch({ url: url });
  42. }
  43. });
  44. }
  45. export default redirectToNewPath;