1.动态生成路由

import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import store from '@/store'
import api from '@/api'Vue.use(Router)const router = new Router({routes: [{path: '/home',name: 'home',component: () => import('@/views/home/home.vue'),children: [],},{path: '/login',name: 'login',component: () => import('@/views/login/login.vue'),},{path: '/error',name: 'error',component: () => import('@/views/error.vue'),}]
})
// const whiteList = ['/login', '/authredirect']// no redirect whitelist
// // 全局钩子
// router.beforeEach((to, from, next) => {
//     let token = localStorage.getItem('token');
//     let userName = localStorage.getItem('user')
//     NProgress.start() // start progress bar
//     console.info(token)
//     // 如果有token
//     // token = 'undefined'
//     if (token !== 'undefined') { // determine if there has token
//       // 登录后进入登录页
//       if (to.path === '/login') {
//         next({path: '/home'})
//         NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
//       } else {
//         addDynamicMenuAndRoutes(userName, to, from)
//         NProgress.done()
//       }
//     } else {
//       /* has no token*/
//       if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
//         next()
//       } else {
//         next('/login') // 否则全部重定向到登录页
//         NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
//       }
//     }
//   }
// )
//
// router.afterEach(() => {
//   NProgress.done() // finish progress bar
// })
router.beforeEach((to, from, next) => {// 登录界面登录成功之后,会把用户信息保存在会话// 存在时间为会话生命周期,页面关闭即失效。let token = localStorage.getItem('token');let userName = localStorage.getItem('user')// token = ""if (to.path === '/login') {// 如果是访问登录界面,如果用户会话信息存在,代表已登录过,跳转到主页if (token) {next({path: '/home'})} else {next()}} else {if (!token) {// 如果访问非登录界面,且户会话信息不存在,代表未登录,则跳转到登录界面next({path: '/login'})} else {// 加载动态菜单和路由addDynamicMenuAndRoutes(userName, to, from)next()}}
})/*** 加载动态菜单和路由*/
function addDynamicMenuAndRoutes(userName, to, from) {// 处理IFrame嵌套页面// handleIFrameUrl(to.path)if (store.state.app.menuRouteLoaded) {console.log('动态菜单和路由已经存在.')return}api.user.findMenus({'username': userName}).then(res => {// 添加动态路由let dynamicRoutes = addDynamicRoutes(res.data)// 处理静态组件绑定路由handleStaticComponent(router, dynamicRoutes)router.addRoutes(router.options.routes)// console.info(JSON.stringify(router.options.routes))// 保存加载状态store.commit('menuRouteLoaded', true)// 保存菜单树store.commit('setNavTree', res.data)}).then(res => {api.user.findPermissions({'username': userName}).then(res => {// 保存用户权限标识集合console.info(JSON.stringify(res.data))store.commit('setPerms', res.data)})})
}/*** 添加动态(菜单)路由* @param {*} menuList 菜单列表* @param {*} routes 递归创建的动态(菜单)路由*/
function addDynamicRoutes(menuList = [], routes = []) {var temp = []for (var i = 0; i < menuList.length; i++) {if (menuList[i].menuChild && menuList[i].menuChild.length >= 1) {temp = temp.concat(menuList[i].menuChild)} else if (menuList[i].path && /\S/.test(menuList[i].path)) {menuList[i].path = menuList[i].path.replace(/^\//, '')// 创建路由配置var route = {path: "/" + menuList[i].path,component: null,name: menuList[i].menuName,meta: {icon: menuList[i].icon,index: menuList[i].menuId,}}try {// 根据菜单URL动态加载vue组件,这里要求vue组件须按照url路径存储// 如url="sys/user",则组件路径应是"@/views/sys/User.vue",否则组件加载不到let array = menuList[i].path.split('/')let url = ''for (let i = 0; i < array.length; i++) {url += array[i].substring(0, 1).toUpperCase() + array[i].substring(1) + '/'}url = url.substring(0, url.length - 1)// console.log(url)route['component'] = resolve => require([`@/views/${url}.vue`], resolve)} catch (e) {}routes.push(route)}}if (temp.length >= 1) {addDynamicRoutes(temp, routes)} else {console.log('动态路由加载...')// console.log(routes)console.log('动态路由加载完成.')}return routes
}/*** 处理路由到本地直接指定页面组件的情况* 比如'代码生成'是要求直接绑定到'Generator'页面组件*/
function handleStaticComponent(router, dynamicRoutes) {// console.info(JSON.stringify(router.options))router.options.routes[0].children = router.options.routes[0].children.concat(dynamicRoutes)
}export default router

动态生成路由 并将菜单信息保存到stroe中去

后台数据为:

[{"menuId":1,"parentId":0,"menuName":"系统管理","path":"/system","component":"/system","perms":null,"icon":"el-icon-s-platform","type":"0","orderNum":2,"createTime":"2017-12-27T08:39:07.000+0000","modifyTime":"2019-01-05T03:13:14.000+0000","menuChild":[{"menuId":3,"parentId":1,"menuName":"用户管理","path":"/system/user","component":"/system/user","perms":"user:view","icon":"el-icon-user-solid","type":"0","orderNum":1,"createTime":"2017-12-27T08:47:13.000+0000","modifyTime":"2019-01-21T22:45:55.000+0000","menuChild":null},{"menuId":4,"parentId":1,"menuName":"角色管理","path":"/system/role","component":"/system/role","perms":"role:view","icon":"el-icon-user","type":"0","orderNum":2,"createTime":"2017-12-27T08:48:09.000+0000","modifyTime":"2018-04-25T01:01:12.000+0000","menuChild":null},{"menuId":6,"parentId":1,"menuName":"部门管理","path":"/system/dept","component":"/system/dept","perms":"dept:view","icon":"iconfont iconzuzhijiagou","type":"0","orderNum":4,"createTime":"2017-12-27T08:57:33.000+0000","modifyTime":"2018-04-25T01:01:40.000+0000","menuChild":null},{"menuId":5,"parentId":1,"menuName":"菜单管理","path":"/system/menus","component":"/system/menus","perms":"menu:view","icon":"el-icon-menu","type":"0","orderNum":3,"createTime":"2017-12-27T08:48:57.000+0000","modifyTime":"2018-04-25T01:01:30.000+0000","menuChild":null},{"menuId":64,"parentId":1,"menuName":"字典管理","path":"/system/dict","component":"/system/dict","perms":"dict:view","icon":"el-icon-tickets","type":"0","orderNum":5,"createTime":"2018-01-18T02:38:25.000+0000","modifyTime":"2018-04-25T01:01:50.000+0000","menuChild":null}]},{"menuId":2,"parentId":0,"menuName":"系统监控","path":"/monitor","component":"/monitor","perms":null,"icon":"el-icon-s-order","type":"0","orderNum":6,"createTime":"2017-12-27T08:45:51.000+0000","modifyTime":"2019-01-22T22:27:12.000+0000","menuChild":[{"menuId":127,"parentId":2,"menuName":"服务器信息","path":"/monitor/systemInfo","component":"/monitor/systemInfo","perms":null,"icon":null,"type":"0","orderNum":3,"createTime":"2019-01-20T23:53:43.000+0000","modifyTime":"2019-01-20T23:57:00.000+0000","menuChild":null},{"menuId":124,"parentId":2,"menuName":"JVM信息","path":"/monitor/jvminfo","component":"/monitor/jvminfo","perms":null,"icon":null,"type":"0","orderNum":1,"createTime":"2019-01-17T18:33:30.000+0000","modifyTime":"2019-01-17T18:46:51.000+0000","menuChild":null},{"menuId":8,"parentId":2,"menuName":"在线用户","path":"/monitor/online","component":"/monitor/online","perms":"user:online","icon":"","type":"0","orderNum":1,"createTime":"2017-12-27T08:59:33.000+0000","modifyTime":"2018-04-25T01:02:04.000+0000","menuChild":null},{"menuId":122,"parentId":2,"menuName":"系统信息","path":"/monitor/system","component":"/monitor/system","perms":null,"icon":null,"type":"0","orderNum":5,"createTime":"2019-01-17T18:31:48.000+0000","modifyTime":"2019-01-17T18:39:46.000+0000","menuChild":null},{"menuId":113,"parentId":2,"menuName":"Redis监控","path":"/monitor/redis","component":"/monitor/redis","perms":"redis:view","icon":null,"type":"0","orderNum":3,"createTime":"2018-06-28T06:29:42.000+0000","modifyTime":null,"menuChild":null},{"menuId":121,"parentId":2,"menuName":"请求追踪","path":"/monitor/httptrace","component":"/monitor/httptrace","perms":null,"icon":null,"type":"0","orderNum":4,"createTime":"2019-01-17T18:30:29.000+0000","modifyTime":null,"menuChild":null},{"menuId":123,"parentId":2,"menuName":"Tomcat信息","path":"/monitor/tomcatinfo","component":"/monitor/tomcatinfo","perms":null,"icon":null,"type":"0","orderNum":2,"createTime":"2019-01-17T18:32:53.000+0000","modifyTime":"2019-01-17T18:46:57.000+0000","menuChild":null}]},{"menuId":144,"parentId":0,"menuName":"坐席服务管理","path":"/service","component":"/service","perms":null,"icon":"el-icon-menu","type":"0","orderNum":4,"createTime":"2017-12-27T08:39:07.000+0000","modifyTime":"2019-01-05T03:13:14.000+0000","menuChild":null},{"menuId":145,"parentId":0,"menuName":"规则管理","path":"/rule","component":"/rule","perms":null,"icon":"el-icon-document","type":"0","orderNum":5,"createTime":"2017-12-27T08:39:07.000+0000","modifyTime":"2019-01-05T03:13:14.000+0000","menuChild":null},{"menuId":142,"parentId":0,"menuName":"主页","path":"/home","component":"/home","perms":null,"icon":"el-icon-s-home","type":"0","orderNum":1,"createTime":"2017-12-27T08:39:07.000+0000","modifyTime":"2019-01-05T03:13:14.000+0000","menuChild":null},{"menuId":143,"parentId":0,"menuName":"知识管理","path":"/knowology","component":"/knowology","perms":null,"icon":"el-icon-location","type":"0","orderNum":3,"createTime":"2017-12-27T08:39:07.000+0000","modifyTime":"2019-01-05T03:13:14.000+0000","menuChild":null}] 

路由加载完成以后通过 菜单管理显示

<template><el-submenu v-if="menu.menuChild && menu.menuChild.length >= 1" :index="menu.parentId+'-'+menu.orderNum"><template slot="title"><i :class="menu.icon"></i><span slot="title">{{menu.menuName}}</span></template><MenuTree v-for="item in menu.menuChild" :key="item.menuId" :menu="item"></MenuTree></el-submenu><el-menu-item v-else :index="menu.parentId+'-'+menu.orderNum" @click="handleRoute(menu)"><i :class="menu.icon"></i><span slot="title">{{menu.menuName}}</span></el-menu-item>
</template><script>export default {name: 'MenuTree',props: {menu: {type: Object,required: true}},methods: {handleRoute(menu) {// 通过菜单URL跳转至指定路由this.$router.push("/" + menu.path)}}}
</script>
<style></style>

遍历所有的路由并显示后  在需要显示的地方调用

<template><div :style="{'background':themeColor}" :class="collapse?'menu-bar-collapse-width':'menu-bar-width'"@mouseenter="collapseOpen" @mouseleave="collapseClose"><el-menu default-active='0' collapse-transition  :style="{'background':themeColor}":collapse="collapse" :class="collapse?'menu-bar-collapse-width':'menu-bar-width'"><menu-tree v-for="item in navTree" :key="item.menuId" :menu="item"></menu-tree></el-menu></div>
</template><script src="@/views/asideContainer/asideContainer.js"></script>
<style scoped src="@/views/asideContainer/asideContainer.scss">
</style>
import {mapState} from 'vuex'
import MenuTree from "@/components/MenuTree"export default {components: {MenuTree},methods: {collapseOpen() {this.$store.commit('collapseOpen')},collapseClose() {this.$store.commit('collapseClose')}},computed: {...mapState({themeColor: state => state.app.themeColor,oldThemeColor: state => state.app.oldThemeColor,collapse: state => state.app.collapse,navTree: state => state.menu.navTree})}
}
<template><div class="wrapper"><header-container></header-container><aside-container></aside-container><main-container></main-container></div>
</template><script src="@/views/home/home.js"></script>
<style src="@/views/home/home.scss"></style>

显示效果为:

vue 权限管理 动态路由(6)相关推荐

  1. Vue权限管理解决方案

    中文 | English vue-access-control :gem: Vue权限管理解决方案 介绍 Vue-Access-Control是一套基于Vue/Vue-Router/axios 实现的 ...

  2. P22-Vue3后台管理系统-权限管理之路由守卫判断⽤户登录状态

    P22-Vue3后台管理系统-权限管理之路由守卫判断⽤户登录状态 文章目录 P22-Vue3后台管理系统-权限管理之路由守卫判断⽤户登录状态 1.概述 2.mock接口返回token 2.1.mock ...

  3. vue权限管理的设计与实现

    一.什么是权限管理 在web应用中权限管理,一般指根据系统设置和分配给某个角色的应用权限,用户可以访问而且只能访问自己被分配的资源.权限管理几乎出现在任何系统里面,在web后台管理系统里面尤为常见. ...

  4. Vue【有与无】【F3】【问题】vue 2.x 动态路由刷新后空白

    先确认在route.js 或者 main.js 中有没有使用路由守卫vue.beforeEach和vue.addRouter() 促使页面每次刷新,重新根据后台返回数据生成动态路由. // 避免路由守 ...

  5. vue实现用户登录验证 + 权限验证 + 动态路由(左侧菜单栏)

    1. 技术栈说明 vue2.6 + vue-router + vuex + element-ui 2. 开始:新建项目 前提条件:在个人电脑上安装好nodejs(我的是14.15.1)之后,利用nod ...

  6. vue根据权限生成动态路由、导航栏

    基本思路: 1,创建vueRouter,用公共路由实例化 2,创建需要根据权限筛选的路由对象(在路由对象,添加必要的权限判断字段) 3,登录完成,由后端配合返回当前用户的权限集合 4,筛选出有权限的路 ...

  7. Vue iView Admin 动态路由菜单加载 前后端分离(springboot 2.x iview admin vue 前后端分离 模型设计器 动态数据权限...

    宣传官网 xb.exrick.cn 在线Demo xboot.exrick.cn 开源版Github地址 github.com/Exrick/x-bo- 开发文档 www.kancloud.cn/ex ...

  8. Vue中实现动态路由

    展示效果: 1.简单配置一个动态路由: 我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件.例如,我们有一个展示商品的组件,对于所有 上架状态 各不相同的商品,都要使用这个组件来渲染.那么,我 ...

  9. vue中设置动态路由

    1.路由设置中设置指定页面都使用固定的视图组件,复用布局里面的导航routerBar,router-view 2.routerBar内部的钩子函数,使用vuex的action方法,获取动态路由配置,存 ...

最新文章

  1. mariadb(第二章)增删改 MariaDB 数据类型
  2. 数据结构与算法(7-4)最短路径(迪杰斯特拉(Dijkstra)算法、弗洛伊德(Floyd)算法)
  3. 爱奇艺员工拿到北京户口后辞职,被判赔偿公司十万!
  4. 腾讯AI战略详解:技术社会与创新图景 | 2017互联网科技创新白皮书重磅首发
  5. os的进程调度(读书笔记)
  6. ruby 作为嵌入脚本时使用的注意事项
  7. 在n个火柴里面拿3根出来拼接成最大三角形的周长
  8. codeforces CF438D The Child and Sequence 线段树
  9. 【Java虚拟机】运行时数据区
  10. 程序员群名称大全_微信群群名技巧和群名称大全(上)
  11. 不要张口别人有问题,先看自己是否做错
  12. android 强制竖排,[Android]实现文字竖排
  13. ubuntu:下载ubuntu内核
  14. serializers.Serializer的用法
  15. 西南交大计算机学校地址,西南交通大学有几个校区及校区地址
  16. 人物专访 | 从《黑客帝国》到《花木兰》的特效,制作人Diana这40年
  17. 学人工智能电脑主机八大件配置选择指南
  18. mysql查询多个部门的子部门,数据库(多表查询,子查询)
  19. 医保异地报销攻略,全国轻松刷卡就医
  20. iPhoneX 安全区域 safe-area-inset-*样式不生效

热门文章

  1. POJ 1003 Hangover 水题
  2. Cisco路由器限速
  3. opencv3 6.2非线性滤波
  4. 老兵新传:Visual Basic核心编程及通用模块开发 pdf电子书
  5. Android MVP的一点理解
  6. Python处理excel-根据全称自动填写简称
  7. 判断用户关闭浏览器-beforeunload事件
  8. 【软考】系统集成项目管理工程师(七)项目范围管理
  9. 第十七届全国大学生智能车竞赛全国总决赛参赛队伍
  10. 计算机毕业设计springboot轰趴馆管理