vue根据后端菜单自动生成路由(动态路由)
router.js
import Vue from 'vue' import Router from 'vue-router' import store from '../store' import generateRouter from './generateRouter' import cookie from './cookie.js' Vue.use(Router) let router = new Router() const getRouter = () => { router.matcher = new Router().matcher//重置路由 router = generateRouter(router) }
// 在菜单改变时调用重新生成菜单 getRouter() // 全局守卫 控制用户未登录状况下的加载 router.beforeEach(async (to, from, next) => { if (to.name) { //路由正确 if (to.matched.some(res => res.meta.requireLogin)) { //需要登录 // 判断是否需要登录权限 if (['true', true].indexOf(cookie.getCookie('isLogin')) > -1) { //判断是否有用户信息 !sessionStorage.getItem('userInfo') && (await store.dispatch('getUserInfo')) //判断是否有权限树信息 !localStorage.getItem('menuList') && (await store.dispatch('getMenuListByUser')) // next() } else { next({ name: 'loginLink1' }) } } else { next() } } else { //路由错误 if (['true', true].indexOf(cookie.getCookie('isLogin')) > -1) { //已经登录 next({ name: 'navigationLink' }) } else { next({ name: 'loginLink1' }) } } }) const originalPush = Router.prototype.push Router.prototype.push = function push(location) { return originalPush.call(this, location).catch(err => err) } export { router, getRouter }
生成菜单generateRouter.js
// import router from './index' // import Router from 'vue-router' // const router = new Router() const routes = [ { path: '/', name: 'indexLink1', component: resolve => require(['@/view/index.vue'], resolve), redirect: '/navigation', meta: { title: '首页', requireLogin: true }, children: [] }, { path: '/navigation', name: 'navigationLink', component: resolve => require(['@/view/navigation/index.vue'], resolve), meta: { title:'导航页', requireLogin: true } }, { path: '/login', name: 'loginLink1', component: resolve => require(['@/view/login/login.vue'], resolve), meta: { requireLogin: false } }, { path: '/404', name: 'unfoundLink', component: resolve => require(['@/view/404.vue'], resolve), meta: { requireLogin: true } }, { path: '/401', name: 'unPermissionLink', component: resolve => require(['@/view/401.vue'], resolve), meta: { requireLogin: true } } ] const generateRouter = (router) => { routes[0].children = [] const menuList = JSON.parse(localStorage.getItem('menuList')) function getAllLeaf(data) { const result = [] function getLeaf(data) { data.forEach(item => { if (!item.hasChild) { result.push(item) } else { getLeaf(item.children) } }) } getLeaf(data) return result } if (menuList && menuList.length !== 0) { const menuLeafList = getAllLeaf(menuList) menuLeafList.forEach(item => { if (item.url) { routes[0].children.push({ path: item.url, name: `${item.url.split('/').join('')}Link`, component: (resolve) => require(['@/view' + item.url + '.vue'], resolve), meta: { requireLogin: true } }) } }) } router.options.routes = [] routes.forEach(item => { router.addRoute(item) router.options.routes.push(item) }) return router } export default generateRouter
cookie.js
const cookie = { /** * 设置cookie * @param cname 名称 * @param cvalue 值 * @param exhours 过期时间(单位:小时) */ setCookie(cname, cvalue, exhours = 0) { let expires = '' if (exhours) { const d = new Date(); d.setTime(d.getTime() + (exhours * 60 * 60 * 1000)); expires = "expires=" + d.toGMTString(); } document.cookie = cname + "=" + cvalue + "; " + expires; }, /** * 获取cookie * @param cname 名称 * @return {string} */ getCookie(cname) { const name = cname + "="; const ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { const c = ca[i].trim(); if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } return ""; } } export default cookie