router.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import VueRouter from 'vue-router'
  2. import { Message } from "element-ui";
  3. import store from "@/store";
  4. import router, { ignore } from '@/router'
  5. import storage from '../utils/storage'
  6. // Remove Navigating to current location (XXX) is not allowed
  7. const routerPush = VueRouter.prototype.push;
  8. VueRouter.prototype.push = function push(location) {
  9. return routerPush.call(this, location).catch((error) => error);
  10. };
  11. export default function () {
  12. router.$plugin = {
  13. addViews: (list, options) => {
  14. if (!options) {
  15. options = {};
  16. }
  17. // Parse route config
  18. list.map((e) => {
  19. if (!e.component) {
  20. let url = e.viewPath;
  21. if (url) {
  22. if (
  23. /^(http[s]?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i.test(
  24. url
  25. )
  26. ) {
  27. e.meta.iframeUrl = url;
  28. e.component = () => import(`cool/components/base/pages/iframe/index.vue`);
  29. } else {
  30. if (url.indexOf("views/") === 0) {
  31. e.component = () => import(`@/${url}`);
  32. } else {
  33. console.error(url, "异常");
  34. }
  35. }
  36. } else {
  37. e.redirect = "/404";
  38. }
  39. }
  40. });
  41. // Batch add route
  42. list.forEach((e) => {
  43. router.addRoute("index", e);
  44. });
  45. // Add 404 rule
  46. if (!options.ignore404) {
  47. router.addRoute({
  48. path: "*",
  49. redirect: "/404"
  50. });
  51. }
  52. },
  53. to: (url) => {
  54. if (router.path != url) {
  55. router.push(url);
  56. }
  57. }
  58. };
  59. router.beforeEach((to, from, next) => {
  60. const { token, browser } = store.getters
  61. if (token) {
  62. if (to.path.indexOf('/login') === 0) {
  63. // 登录成功且 token 未过期,回到首页
  64. if (!storage.isExpired('token')) {
  65. return next('/')
  66. }
  67. } else {
  68. // 添加路由进程
  69. store.commit("ADD_PROCESS", {
  70. label: (to.meta && to.meta.label) || to.name,
  71. value: to.fullPath
  72. });
  73. }
  74. } else {
  75. if (!ignore.token.some((e) => to.path.indexOf(e) === 0)) {
  76. return next("/login");
  77. }
  78. }
  79. // H5 下关闭左侧菜单
  80. if (browser.isMobile) {
  81. store.commit("COLLAPSE_MENU", true);
  82. }
  83. next()
  84. })
  85. let lock = false;
  86. router.onError((err) => {
  87. if (!lock) {
  88. lock = true;
  89. if (err.code == "MODULE_NOT_FOUND") {
  90. console.error(err.message.replace("Cannot find module ", ""), "路由组件不存在");
  91. Message.error(`路由组件路径错误`);
  92. } else {
  93. console.error(err);
  94. }
  95. setTimeout(() => {
  96. lock = false;
  97. }, 0);
  98. }
  99. });
  100. }