You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

86 lines
2.8 KiB

  1. import queryParams from '../../libs/function/queryParams.js';
  2. /**
  3. * 路由跳转
  4. * 注意:本方法没有对跳转的回调函数进行封装
  5. */
  6. function route(options = {}, params = false) {
  7. let config = {
  8. type: 'navigateTo',
  9. url: '',
  10. delta: 1, // navigateBack页面后退时,回退的层数
  11. params: {}, // 传递的参数
  12. animationType: 'pop-in', // 窗口动画,只在APP有效
  13. animationDuration: 300, // 窗口动画持续时间,单位毫秒,只在APP有效
  14. };
  15. config = Object.assign(config, options);
  16. // 如果url没有"/"开头,添加上,因为uni的路由跳转需要"/"开头
  17. if (config.url[0] != '/') config.url = '/' + config.url;
  18. // 判断是否有传递显式的参数,Object.keys转为数组并判断长度,switchTab类型时不能携带参数
  19. if (Object.keys(config.params).length && config.type != 'switchTab') {
  20. // 判断用户传递的url中,是否带有参数
  21. // 使用正则匹配,主要依据是判断是否有"/","?","="等,如“/page/index/index?name=mary"
  22. // 如果有url中有get参数,转换后无需带上"?"
  23. let query = '';
  24. if (/.*\/.*\?.*=.*/.test(config.url)) {
  25. // object对象转为get类型的参数
  26. query = queryParams(config.params, false);
  27. // 因为已有get参数,所以后面拼接的参数需要带上"&"隔开
  28. config.url += "&" + query;
  29. } else {
  30. query = queryParams(config.params);
  31. config.url += query;
  32. }
  33. }
  34. // 简写形式,把url和参数拼接起来
  35. if (typeof options === 'string' && typeof params == 'object') {
  36. let query = '';
  37. if (/.*\/.*\?.*=.*/.test(options)) {
  38. // object对象转为get类型的参数
  39. query = queryParams(params, false);
  40. // 因为已有get参数,所以后面拼接的参数需要带上"&"隔开
  41. options += "&" + query;
  42. } else {
  43. query = queryParams(params);
  44. options += query;
  45. }
  46. }
  47. // 判断是否一个字符串,如果是,直接跳转(简写法)
  48. // 如果是中情形,默认第二个参数为对象形式的参数
  49. if (typeof options === 'string') {
  50. if (options[0] != '/') options = '/' + options;
  51. return uni.navigateTo({
  52. url: options
  53. });
  54. }
  55. // navigateTo类型的跳转
  56. if (config.type == 'navigateTo' || config.type == 'to') {
  57. return uni.navigateTo({
  58. url: config.url,
  59. animationType: config.animationType,
  60. animationDuration: config.animationDuration,
  61. });
  62. }
  63. if (config.type == 'redirectTo' || config.type == 'redirect') {
  64. return uni.redirectTo({
  65. url: config.url,
  66. });
  67. }
  68. if (config.type == 'switchTab' || config.type == 'tab') {
  69. return uni.switchTab({
  70. url: config.url,
  71. });
  72. }
  73. if (config.type == 'reLaunch') {
  74. return uni.reLaunch({
  75. url: config.url
  76. });
  77. }
  78. if (config.type == 'navigateBack' || config.type == 'back') {
  79. return uni.navigateBack({
  80. delta: parseInt(config.delta ? config.delta : this.delta)
  81. });
  82. }
  83. }
  84. export default route;