hackRoute.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /**
  2. * hack uniapp的路由函数b
  3. * @param {Function} callback
  4. * @return {never}
  5. */
  6. export const hackUniRoute = function (callback) {
  7. // 路由跳转的函数key值
  8. const UNI_ROUTE_ACTIONS = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab', 'navigateBack'];
  9. // 函数缓存容器
  10. const cacheFunc = {};
  11. // 保存原函数引用
  12. UNI_ROUTE_ACTIONS.forEach((key) => {
  13. cacheFunc[key] = uni[key];
  14. });
  15. // 重写方法
  16. UNI_ROUTE_ACTIONS.forEach((key) => {
  17. uni[key] = (opts, routeGuardsOpts) => {
  18. // 取消拦截并直接运行
  19. if (routeGuardsOpts === false) {
  20. cacheFunc[key](opts);
  21. } else {
  22. // 处理所有钩子
  23. const defaultOpts = { action: key };
  24. const newOpts = Object.assign(defaultOpts, opts);
  25. const actionFunc = function (customOpts) {
  26. const lastOpts = Object.assign(newOpts, customOpts);
  27. cacheFunc[lastOpts.action](lastOpts);
  28. };
  29. callback.call(this, newOpts, actionFunc);
  30. }
  31. };
  32. });
  33. };