proxy.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { beforeEnterHooks } from '../concat';
  2. import { vuelifeHooks } from '../base';
  3. import MyArray from '../extends/myArray';
  4. /**
  5. * 通过 Object.defineProperty 代理一个对象主要是拦截beforeEnter 生命钩子
  6. * @param {Router} Router 路由实例对象
  7. * @param {Object} BeProxy 需要代理的路由表
  8. */
  9. export const proxyBeforeEnter = function (Router, BeProxy) {
  10. const proxyDc = Object.create(null);// 创建没有继承的属性
  11. const BeProxyKeys = Object.keys(BeProxy);
  12. for (let i = 0; i < BeProxyKeys.length; i += 1) {
  13. const key = BeProxyKeys[i];
  14. Object.defineProperty(proxyDc, key, {
  15. enumerable: true,
  16. configurable: true,
  17. get() {
  18. const value = BeProxy[key];
  19. if (key == 'beforeEnter' && value !== undefined) {
  20. return (to, from, next) => {
  21. beforeEnterHooks(to, from, next, value, Router);
  22. };
  23. }
  24. return value;
  25. },
  26. set(v) {
  27. BeProxy[key] = v;
  28. },
  29. });
  30. }
  31. return proxyDc;
  32. };
  33. /**
  34. * 在uni-app没有注入生命周期时先直接代理相关生命周期数组
  35. * @param {Object} Router
  36. * @param {Object} key
  37. * @param {Funtion} hookFun
  38. */
  39. export const proxyEachHooks = function (Router, key, hookFun) {
  40. const vueOldHooks = vuelifeHooks[key];
  41. return new MyArray(Router, vueOldHooks, hookFun);
  42. };