vue pc项目 router.js 配置详解

这个是我之前一个项目的router.js 文件

import Vue from 'vue'
import http from './plugins/axios'
import Router from 'vue-router'
import { getChnPinyin } from "@/utils/chnpinyin";
import { clearLoginInfo, handlerMenu } from '@/utils'

Vue.use(Router)
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

/**
 * 全局路由
 */
const globalRoutes = [
  {
    path: '/login',
    name: 'login',
    meta: {
      title: "登录",
    },
    isHide: true,
    component: () => import(/* webpackChunkName: 'login' */ "./views/login")
  },
  {
    path: '/404',
    name: "404",
    isHide: true,
    component: () => import("./views/404")
  }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = [{
  path: '/',
  name: 'main',
  meta: {
    title: "主页",
  },
  redirect: { name: 'home' },
  component: () => import(/* webpackChunkName: 'main' */ './views/main'),
  children: [
    {
      path: "/home",
      name: "home",
      meta: {
        title: "主页",
        icon: "fa-zhuye"
      },
      component: () => import(/* webpackChunkName: 'main' */ './views/home')
    },
    {
      path: "/userinfo",
      name: "userinfo",
      meta: {
        title: "用户信息"
      },
      isHide: true,
      component: () => import(/* webpackChunkName: 'user' */ "./views/modules/user"),
      children: [
        {
          path: "profile",
          name: "profile",
          meta: {
            title: "基本信息"
          },
          component: () => import(/* webpackChunkName: 'userprofile' */ "./views/modules/user/profile")
        },
        {
          path: "pwmanage",
          name: "pwmanage",
          meta: {
            title: "修改密码"
          },
          component: () => import(/* webpackChunkName: 'userpwmanage' */ "./views/modules/user/pwmanage")
        },
      ]
    },
    {
      path: '/wsview',
      name: 'wsview',
      meta: {
        title: "查看文书",
        icon: "fa-zhuye"
      },
      isHide: true,
      component: () => import(/* webpackChunkName: 'wsviewer' */ "./views/wsviewer")
    },
    {
      path: "/yuejuan",
      name: "yuejuan",
      meta: {
        title: "阅卷",
      },
      isHide: true,
      component: () => import(/* webpackChunkName: 'yuejuan' */ "./views/yuejuan")
    }
  ],
  beforeEnter(to, from, next) {
    let token = ''
    if (window.top == window.self) {
      token = Vue.cookie.get('token')
    } else if (window.top !== window.self) {
      token = window.localStorage.getItem("token")
    } else {
      token = window.localStorage.getItem("token")
    }
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
    }
    next()
  }
}]


/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
  let temp = []
  for (let i = 0; i < globalRoutes.length; i++) {
    if (route.name === globalRoutes[i].name/* route.path === globalRoutes[i].path */) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

const router = new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  base: process.env.BASE_URL,
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  console.log(to, from, next)
  if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
    next()
  } else {
    http({
      url: '/sys/menu/nav',
      method: 'get',
      notip: true,
    }).then(({ data }) => {
      console.log(data);
      if (data.code == "0000" || data.code == "0") {
        var dat = data;
        var nlist = handlerMenu(dat.menuList)
        console.log(nlist)
        //先清除路由再动态添加
        resetRouter();
        fnAddDynamicMenuRoutes(nlist, [])
        router.options.isAddDynamicMenuRoutes = true
        sessionStorage.setItem('menuList', JSON.stringify(nlist || '[]'))
        sessionStorage.setItem('permissions', JSON.stringify(dat.permissions || '[]'))
        sessionStorage.setItem('dictList', JSON.stringify(dat.dictList || '[]'))
        sessionStorage.setItem('orgList', JSON.stringify(dat.orgList || '[]'))
        sessionStorage.setItem('userList', JSON.stringify(dat.userList || '[]'))
        router.replace(to)
      } else {
        sessionStorage.setItem('menuList', '[]')
        sessionStorage.setItem('permissions', '[]')
        sessionStorage.setItem('dictList', '[]')
        sessionStorage.setItem('orgList', '[]')
        sessionStorage.setItem('userList', '[]')
        next()
      }
    }).catch((e) => {
      console.error(e);
      console.log(`%c${e} 请求菜单列表和权限失败,跳转至登录页!!`, 'color:blue')
      // router.push({ name: 'login' })
      // router.replace({path:"/login"});
      // setTimeout(()=>{
      //   location.reload();
      // },200)
    })
  }
})

function resetRouter() {
  const newRouter = new Router({
    mode: 'history',
    scrollBehavior: () => ({ y: 0 }),
    base: process.env.BASE_URL,
    routes: globalRoutes.concat(mainRoutes)
  });
  router.matcher = newRouter.matcher; // reset router
}

function diguiAddMenu(list, pid) {
  for (let i = 0; i < list.length; i++) {
    let v = list[i];
    v.meta = {
      title: v.name,
      icon: v.icon,
      isDynamic: true,
      menuId: v.menuId,
      fg: v.fg,
      datasource: v.datasource,
      compareModuleId: v.compareModuleId,
      blockColorParams: v.blockColorParams ? JSON.parse(v.blockColorParams) : []
    }
    v.title = v.name;
    if (v.url) {
      v.path = v.url.split("/").pop();
      v.name = v.url.split("/").pop();
    } else {
      v.path = getChnPinyin(v.name);
      v.name = getChnPinyin(v.name);
    }
    console.log(v.url);
    v.component = () => import(/* webpackChunkName: 'jumpper' */ "./views/jump");
    if (!v.datasource || v.datasource == "local") {
      // obj.realComponent = _import("modules/"+(v.url.indexOf("sys")>-1?v.url:v.url+"/index"));
      v.realComponent = v.url ? ("modules/" + (v.url + "/index")) : "modules/common/index";
    }

    if (v.list) {
      v.children = v.list;
      diguiAddMenu(v.list);
    }
  }
}

function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  diguiAddMenu(menuList);
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children[0]) {
      menuList[i].redirect = { name: menuList[i].children[0].name }
    }
    routes.push(menuList[i]);
  }
  mainRoutes[0].children = mainRoutes[0].children.concat(routes);

  console.log(router);
  router.addRoutes([
    mainRoutes[0],
    { path: '*', redirect: { name: '404' } }
  ])
  console.log(mainRoutes)
}


export default router;

你可能感兴趣的:(javascript,vue.js,前端)