登录是获取添加的路由,存在vuex中
login.vue

  import {initRoutes} from "@/router/index.js"; // 按需引入路由的动态注入方法//获取要添加的路由
let navList = [{module: "system",children: [{id: 1,path: "/system/marketTopics",icon: "icon-shichang",title: "市场主体专题",},{id: 2,path: "/system/floorTopics",icon: "icon-changfang",title: "楼宇厂房载体专题",},{id: 3,path: "/system/industryTopics",icon: "icon-xiangmu",title: "产业项目专题",}, {id: 4,path: "/system/user",icon: "el-icon-menu",title: "用户管理",},],},{module: "user",children: [{id: 1,path: "/user",icon: "el-icon-menu",title: "用户管理",},],},
];
// 存在vueX中
this.$store.commit("setNavList", navList);// 动态添加路由
initRoutes();

vueX代码如下:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)export default new Vuex.Store({state: {// 动态路由navList: JSON.parse(window.sessionStorage.getItem('navList') || '[]')},mutations: {// 动态路由setNavList(state, data) {state.navList = data;window.sessionStorage.setItem("navList", JSON.stringify(data));}},actions: {},modules: {}
})

router/index.js 路由配置文件代码如下

import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'import Login from '@/views/Login'
import Index from '@/views/Index'import Error from '@/views/Error'
import NotFound from '@/views/NotFound'
// 数据管理
import System from '@/views/System'
import MarketTopics from '@/views/System/MarketTopics' //市场主体专题
import FloorTopics from '@/views/System/FloorTopics' //楼宇厂房专题
import IndustryTopics from '@/views/System/IndustryTopics' //产业项目专题
import User1 from '@/views/System/User' //用户管理
// 用户管理
import User from '@/views/User'// 需要动态添加的路由
const marketTopics = { path: '/system/marketTopics', component: MarketTopics }
const floorTopics = { path: '/system/floorTopics', component: FloorTopics }
const industryTopics = { path: '/system/industryTopics', component: IndustryTopics }
const user = { path: '/system/User', component: User1 }
// 动态路由根据名称匹配跳转页面
const ruleMapping = {'/system/marketTopics': marketTopics,'/system/floorTopics': floorTopics,'/system/industryTopics': industryTopics,'/system/user': user,
};Vue.use(VueRouter)// 创建默认路由
const createRouter = () => new VueRouter({// mode: 'history',base: '/', // 打包时需要配置访问目录routes: [{path: '/',redirect: "/login"}, {path: '/login',component: Login}, {path: '/index',component: Index,name:"Index",}, {path: '/notFound',name: 'notFound',component: NotFound}, {// 没有路由的访问权限时,访问的页面404path: '*',component: Error}]
})const router = createRouter();/* 路由导航守卫to 要跳转到哪个界面from 从哪跳转来的next 是否要放行
*/
router.beforeEach((to, from, next) => {if (to.path === '/login') {// 如果是要跳转登录就直接放行next()} else {// 检查路由元信息,是否开启登录验证if (to.matched.some(record => record.meta.requiresAuth)) {const token = store.state.user.token;// 判断用户是否已经登录if (!token) {// 没登陆还是跳转登录页next('/notFound')} else {// 正常情况就放行,设置当前路由地址window.sessionStorage.setItem('activePath', to.path)next()}} else {// 没开启登录验证,放行next()}}
});
// 解决 Vue 重复点击相同路由,出现 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation 问题
const VueRouterPush =VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {return VueRouterPush.call(this, to).catch(err => err)
}// 动态导入路由
export function initRoutes() {const token = store.state.user.token;if (!token) {router.login} else {const currentRoutes = router.options.routes; // 获取要添加路由的当前路由const navList = store.state.navList; // 获取state中缓存的根据权限获取的路由if (navList.length > 0) {const currentIndex = { path: '/system', component: System, children: [] }let currentUser = ""navList.forEach(item => { // 循环获取的路由if (item.module == "system") {const list = item.childrenconst redirect = list[0].path;currentIndex.redirect = redirectlist.forEach((t, i) => {const temp = ruleMapping[t.path]; // 获取需要动态添加的路由,对应的跳转页面配置currentIndex.children.push(temp); // 将匹配的路由,添加到当前路由的对应子路由位置})} else if (item.module == "user") {currentUser = { path: '/user', component: User, children: [] }currentRoutes.push(currentUser);}});currentRoutes.push(currentIndex);router.addRoutes(currentRoutes); // 执行动态添加路由方法,完成动态路由添加}}
}// 重置路由(退出登录,切换账号)
export function resetRouter() {const newRouter = createRouter()router.matcher = newRouter.matcher // the relevant partrouter.options = newRouter.options;
}export default router

解决刷新页面路由丢失问题,在APP.vue文件下调用initRoutes
代码如下:

<template><div id="app"><router-view></router-view></div>
</template><script>
import { initRoutes } from '@/router/index.js'
export default {created() {// 生命周期内,刷新时重新动态添加组件,防止刷新后路由丢失initRoutes()}
}
</script><style>
#app {height: 100%;
}
</style>

— 优化开始 — --- 优化开始 — --- 优化开始 — --- 优化开始 — --- 优化开始 —
使用动态路由加addRoutes(优化两个文件代码,其他同上)
登录时存入vuex

  // 存储权限列表let navList = [{module: 'index',isOnePage: false,name: '首页',list: [{id: 1,title: '地图首页',icon: '',path: '/index/home',children: []} ]}];if (userObj.type == '1') {// 假设是管理员用户,添加后台管理页面权限navList[0].list.push({id: 2,title: '后台管理',icon: '',path: '/index/system',children: [{id: 21,title: '传染病信息统计',icon: 'icon-chuanranbingguanli',path: '/index/system/attack'},{id: 24,title: '传染病时序数据管理',icon: 'icon-jiancedianshishijiance',path: '/index/system/infection'},{id: 23,title: '监测点信息管理',icon: 'icon-shujuguanli',path: '/index/system/survey'},{id: 22,title: '采样点信息管理',icon: 'icon-caiyangjilu',path: '/index/system/sampling'},{id: 25,title: '模型管理',icon: 'icon-moxingshezhi',path: '/index/system/model'},{id: 26,title: '预警结果',icon: 'icon-hetongyujing',path: '/index/system/warnResult'},{id: 10,title: '用户管理',icon: 'icon-zhanghaoshenhe',path: '',children:[{id: 10,title: '账号管理',icon: '',path: '/index/system/user',},]},]})}this.$store.commit('setNavList', navList);// 存入vuex中(vuex同上)

router.js(添加动态路由,优化initRoutes方法)

import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'const Login = () => import('@/views/Login');
const Error = () => import('@/views/Error');
const NotFound = () => import('@/views/NotFound');const Index = () => import('@/views/Index');
const Home = () => import('@/views/Home');
const System = () => import('@/views/System');
const Attack = () => import('@/views/System/Attack');
const Infection = () => import('@/views/System/Infection');
const Sampling = () => import('@/views/System/Sampling');
const Model = () => import('@/views/System/Model');
const WarnResult = () => import('@/views/System/WarnResult');
const Survey = () => import('@/views/System/Survey');
const User = () => import('@/views/System/User');// 需要动态添加的路由
const index = {path: '/index', component: Index}
const home = {path: '/index/home', component: Home}
const system = {path: '/index/system', component: System}
const attack = {path: '/index/system/attack', component: Attack}
const infection = {path: '/index/system/infection', component: Infection}
const sampling = {path: '/index/system/sampling', component: Sampling}
const model = {path: '/index/system/model', component: Model}
const warnResult = {path: '/index/system/warnResult', component: WarnResult}
const survey = {path: '/index/system/survey', component: Survey}
const user = {path: '/index/system/user', component: User}
// 动态路由根据名称匹配跳转页面
const ruleMapping = {'/index': index,'/index/home': home,'/index/system': system,'/index/system/attack': attack,'/index/system/infection': infection,'/index/system/sampling': sampling,'/index/system/model': model,'/index/system/warnResult': warnResult,'/index/system/survey': survey,'/index/system/user': user,
};Vue.use(VueRouter)// 创建默认路由
const createRouter = () => new VueRouter({// mode: 'history',base: '/', // 打包时需要配置访问目录routes: [{path: '/',redirect: "/login"}, {path: '/login',component: Login}, {path: '/notFound',name: 'notFound',component: NotFound}]
})const router = createRouter();/* 路由导航守卫to 要跳转到哪个界面from 从哪跳转来的next 是否要放行
*/
router.beforeEach((to, from, next) => {if (to.path === '/login') {// 如果是要跳转登录就直接放行next()} else {// 检查路由元信息,是否开启登录验证if (to.matched.some(record => record.meta.requiresAuth)) {const token = store.state.user.token;// 判断用户是否已经登录if (!token) {// 没登陆还是跳转登录页next('/notFound')} else {// 正常情况就放行,设置当前路由地址window.sessionStorage.setItem('activePath', to.path)next()}} else {// 没开启登录验证,放行next()}}
});// 动态导入路由
export function initRoutes() {const token = store.state.user.token;if (!token) {router.login} else {const currentRoutes = router.options.routes; // 获取要添加路由的当前路由const navList = store.state.navList; // 获取state中缓存的根据权限获取的路由navList.forEach(item => { // 循环获取的路由// 不是单页// 首先获取模块第一个路由的地址,配置模块默认访问页面let firstPath = ""if (item.list && item.list.length > 0) {firstPath = item.list[0].path;if (firstPath === '' || firstPath == null) {firstPath = item.list[0].children[0].path;}}let currentIndex = {path: `/${item.module}`,component: ruleMapping[`/${item.module}`].component,meta: {requiresAuth: true},redirect: firstPath,children: []};currentRoutes.splice(1, 0, currentIndex);currentRoutes.push({//push 404页面,解决刷新后404闪现问题// 没有路由的访问权限时,访问的页面404path: '*',component: Error})// 循环添加子页面路由if (item.list && item.list.length > 0) {item.list.forEach(item2 => { // 循环获取的路由let temp = ruleMapping[item2.path]; // 获取需要动态添加的路由,对应的跳转页面配置let childrenArr = []if (item2.children.length > 0) {item2.children.forEach(item3 => {if (item3.path === '' || item3.path == null) {item3.children.forEach(item4 => {let temp = ruleMapping[item4.path]; // 获取需要动态添加的路由,对应的跳转页面配置childrenArr.push(temp); // 将匹配的路由,添加到当前路由的对应子路由位置});} else {let temp = ruleMapping[item3.path]; // 获取需要动态添加的路由,对应的跳转页面配置childrenArr.push(temp); // 将匹配的路由,添加到当前路由的对应子路由位置}});}temp["children"] = childrenArr; // 将匹配的路由,添加到当前路由的对应子路由位置temp["redirect"] = childrenArr[0]currentIndex.children.push(temp); // 将匹配的路由,添加到当前路由的对应子路由位置});}});router.addRoutes(currentRoutes); // 执行动态添加路由方法,完成动态路由添加}
}// 重置路由(退出登录,切换账号)
export function resetRouter() {const newRouter = createRouter();router.matcher = newRouter.matcher; // the relevant partrouter.options = newRouter.options;
}export default router

— 优化结束 — --- 优化结束 — --- 优化结束 — --- 优化结束 — --- 优化结束 —

使用addRoutes动态添加路由相关推荐

  1. addroutes刷新_vue 解决addRoutes动态添加路由后刷新失效问题

    前言 某些场景下我们需要利用addRoutes动态添加路由,但是刷新后就会失效,前段时间项目里刚好遇到了这个应用场景,所以就花时间研究了一下,做下分享跟记录,说的不对的地方,请大家指正. 应用场景:用 ...

  2. vue当中addRoutes动态添加路由白屏解决和next(),next(“/“)的一些区别

    问题产生前言 使用动态添加路由router.addRoutes()后进入一个页面,对着这一个页面刷新一下,然后页面就白屏了并且不管刷新多少次都没有用,依旧是白屏,只有重新进入页面才有效果 比如对于网站 ...

  3. 通过addroutes动态添加路由

    说明:addroutes是用来动态添加路由的,在做权限管理的时候会用到这个api,接下来我们一起来探究一下这个api吧. 一.addroutes的使用 1.router/index.js import ...

  4. activemenu怎么拼 vue_vue-element-admin登录逻辑,以及动态添加路由,显示侧边栏

    这段时间在研究element-admin,感觉这个库有许多值得学习的地方,我学习这个库的方法是,先看它的路由,顺着路由,摸清它的逻辑,有点像顺藤摸瓜. 这个库分的模块非常清晰,适合多人合作开发项目,但 ...

  5. vue 动态添加路由

    为什么80%的码农都做不了架构师?>>>    最近在研究权限的相关东西,自然动态加载路由信息少不了.接下来我就来专门记录下我研究的东西. 1.首先后端代码返回一个对象,用java写 ...

  6. Vue2.x动态添加路由实现

    适用于:Vue2.x VueRouter3.x 动态添加路由一般应用于受权限控制的路由菜单,由后端返回可以判断该角色具有的权限,前端处理出一份符合权限的路由表,使用addRoutes方法动态添加权限路 ...

  7. vue的动态路由(登录之后拿到动态路由通过addRouters()动态添加路由)

    登录后我们拿到路由动态路由,后端传的数据可能为这个 {path: '/index',meta: {title: '首页',icon: 'icon-shouye',tab_index: 0, //给头部 ...

  8. vue2.0 + router 3. 0 动态添加路由

    3月11日 周五 作日回顾 .动态添加路由 实现语句 vue 2.0使用 this.$router.addRoutes(); this.$router.addRoutes(currRoutes);// ...

  9. 动态添加路由 addRoute添加路由刷新404

    文章目录 动态添加路由 案例 初步 动态添加路由-使用导航守卫 解决刷新404问题 完整代码: 动态添加路由 大概简而言之,就是需要路由是可以按照项目需求进行配置添加的,而不是一开始就配置好的. 就好 ...

最新文章

  1. 网络推广下叮咚买菜已完成D轮融资,生鲜电商下一次融资又在何方?
  2. ab的压力测试(转)
  3. 如何成为一位牛逼的高手
  4. C++学习之路 | PTA乙级—— 1032 挖掘机技术哪家强 (20 分)(精简)
  5. anaconda python3.8目录_MacBook Pro 安装anaconda、配置环境
  6. MYSQL的随机查询的实现方法
  7. 销售面销五个最基础步骤步骤_3个步骤,可提供强有力的反馈
  8. Win11 BitLocker驱动器加密怎么使用
  9. 我所期待的vs2007
  10. ruby DBI安装使用指南
  11. a中嵌套div的问题
  12. php fread 逐行读取,php fread函数使用方法总结
  13. 【新功能】摹客Figma插件功能升级!标注切图效率加倍
  14. VC版 MFC程序对话框资源移植
  15. 软件版本中的Alpha,Beta,RC,Trial是什么意思?
  16. 二、PHP基础学习之常用命令①
  17. 电流感应放大器应用技术要点
  18. 设计模式与软考试题之职责链模式
  19. 用OutLook发手机短信
  20. 盲沟低比?不不不,是芒果的笔,今天学一下分布式文件存储数据库MongoDB。

热门文章

  1. Leaf-美团分布式id生成系统
  2. 如何让一款没什么差异的产品,从“好”变成“更好”?
  3. windows7系统windows XP系统ps2针孔老式键盘开机不能使用驱动出现感叹号--亲自测试可以解决问题
  4. 谈PHP发展前景和就业解析 -兄弟连IT教育
  5. html显示与隐藏元素的几种方式
  6. 设计模式在ssh中的典型应用
  7. 项目现场的疑难杂症之攻略
  8. 从马尔科夫过程到吉布斯采样(附程序示例)
  9. vue 实现阿里云 “直播Aliplayer” 插件的封装以及调用
  10. 企业固态和普通民用固态 及intel企业固态命名规则