init.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { afterHooks, beforeHooks, registerRouter } from './concat';
  2. import { fromatRoutes } from './util';
  3. import { err, warn } from '../helpers/warn';
  4. import { proxyEachHooks } from './proxy/proxy';
  5. /**
  6. * 重写掉H5端 uni-app原始存在的bug
  7. *
  8. * @param {Object} Router
  9. */
  10. const rewriteUniFun = function (Router) {
  11. if (Router.CONFIG.h5.rewriteFun === false) { // 不需要重写
  12. return false;
  13. }
  14. uni.reLaunch = function ({
  15. url,
  16. }) {
  17. if (url === '/') {
  18. warn('H5端 uni.reLaunch(\'/\')时 默认被重写了! 你可以使用 this.$Router.replaceAll() 或者 uni.reLaunch(\'/\'?xxx)');
  19. // eslint-disable-next-line
  20. if (history.length > 1) { // 只有在有历史记录的时候才返回 不然直接返回首页
  21. return Router.back();
  22. }
  23. return Router.replaceAll('/');
  24. }
  25. const path = url.match(/^[^?]+|(\/)/)[0];
  26. try {
  27. const query = {};
  28. url.replace(/([^?&]+)=([^?&]+)/g, (s, v, k) => {
  29. query[v] = decodeURIComponent(k);
  30. return `${k}=${v}`;
  31. });
  32. Router.replaceAll({
  33. path,
  34. query,
  35. });
  36. } catch (e) {
  37. err(`${url}解析失败了.... 试试 this.$Router.replaceAll() 吧`);
  38. }
  39. };
  40. uni.navigateBack = function (delta) {
  41. let backLayer = delta;
  42. if (delta.constructor === Object) { // 这种可能就只是uni-app自带的返回按钮,还有种可能就是开发者另类传递的
  43. backLayer = 1;
  44. }
  45. Router.back(backLayer, delta);
  46. };
  47. };
  48. /**
  49. * 拦截并注册vueRouter中的生命钩子,路由表解析
  50. * @param {Object} Router
  51. * @param {vueRouter} vueRouter
  52. */
  53. const init = function (Router, vueRouter) {
  54. const CONFIG = Router.CONFIG.h5;
  55. vueRouter.afterHooks = proxyEachHooks(Router, 'afterHooks', afterHooks);
  56. vueRouter.beforeHooks = proxyEachHooks(Router, 'beforeHooks', beforeHooks);
  57. const objVueRoutes = fromatRoutes(vueRouter.options.routes, false, {}); // 返回一个格式化好的routes 键值对的形式
  58. const objSelfRoutes = fromatRoutes(Router.CONFIG.routes, true, CONFIG);
  59. Router.vueRoutes = objVueRoutes; // 挂载vue-routes到当前的路由下
  60. Router.selfRoutes = {
  61. ...Router.selfRoutes || {},
  62. ...objSelfRoutes,
  63. }; // 挂载self-routes到当前路由下
  64. Router.$route = vueRouter; // 挂载vue-router到$route
  65. rewriteUniFun(Router); // 重新掉uniapp上的一些有异常的方法
  66. registerRouter(Router, vueRouter, CONFIG.vueRouterDev);
  67. };
  68. export default init;