layRouter.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /** EasyWeb spa v3.1.6 date:2020-02-08 License By http://easyweb.vip */
  2. layui.define(function (exports) {
  3. var router = {
  4. index: '/',
  5. lash: null,
  6. routers: {},
  7. init: function (options) {
  8. router.index = router.routerInfo(options.index).path.join('/');
  9. if (options.pop && typeof options.pop === 'function') {
  10. router.pop = options.pop;
  11. }
  12. if (options.notFound && typeof options.notFound === 'function') {
  13. router.notFound = options.notFound;
  14. }
  15. onhashchange();
  16. window.onhashchange = function () {
  17. onhashchange();
  18. };
  19. return this;
  20. },
  21. /* 注册路由 */
  22. reg: function (hash, handler) {
  23. if (hash) {
  24. if (!handler) {
  25. handler = function () {
  26. };
  27. }
  28. if (hash instanceof Array) {
  29. for (var i in hash) {
  30. this.reg.apply(this, [hash[i], handler]);
  31. }
  32. } else if (typeof hash === 'string') {
  33. hash = router.routerInfo(hash).path.join('/');
  34. if (typeof handler === 'function') {
  35. router.routers[hash] = handler;
  36. } else if (typeof handler === 'string' && router[handler]) {
  37. router.routers[hash] = router.routers[handler];
  38. }
  39. }
  40. }
  41. return this;
  42. },
  43. /* 获取路由信息 */
  44. routerInfo: function (url) {
  45. url || (url = location.hash);
  46. var hash = url.replace(/^#+/g, '').replace(/\/+/g, '/');
  47. if (hash.indexOf('/') !== 0) {
  48. hash = '/' + hash;
  49. }
  50. return layui.router('#' + hash);
  51. },
  52. /* 刷新路由 */
  53. refresh: function (url) {
  54. onhashchange(url, true);
  55. },
  56. /* 跳转路由 */
  57. go: function (hash) {
  58. location.hash = '#' + router.routerInfo(hash).href;
  59. }
  60. };
  61. function onhashchange(url, refresh) {
  62. var routerInfo = router.routerInfo(url);
  63. router.lash = routerInfo.href;
  64. var hash = routerInfo.path.join('/');
  65. if (!hash || hash === '/') {
  66. hash = router.index;
  67. routerInfo = router.routerInfo(router.index);
  68. }
  69. router.pop && router.pop.call(this, routerInfo);
  70. if (router.routers[hash]) {
  71. routerInfo.refresh = refresh;
  72. router.routers[hash].call(this, routerInfo);
  73. } else if (router.notFound) {
  74. router.notFound.call(this, routerInfo);
  75. }
  76. }
  77. exports('layRouter', router);
  78. });