关于vue中根据用户权限动态添加路由的问题

 更新时间:2021年11月05日 10:52:46   作者:一只烛  
每次路由发生变化时都需要调用一次路由守卫,并且store中的数据会在每次刷新的时候清空,因此需要判断store中是否有添加的动态路由,本文给大家分享vue中根据用户权限动态添加路由的问题,感兴趣的朋友一起看看吧

根据用户的权限,展示不同的菜单页。

知识点

路由守卫(使用了前置守卫):根据用户角色判断要添加的路由
vuex:保存动态添加的路由

难点

每次路由发生变化时都需要调用一次路由守卫,并且store中的数据会在每次刷新的时候清空,因此需要判断store中是否有添加的动态路由。
(若没有判断 则会一直添加 导致内存溢出)

在这里插入图片描述

根据角色判断路由
过滤动态路由 判断每条路由角色是否与登录传入的角色一致

在这里插入图片描述

<template>
  <div>
    <el-menu
      :default-active="$route.path"
      class="el-menu-vertical-demo menu_wrap"
      background-color="#324057"
      text-color="white"
      active-text-color="#20a0ff"
      :collapse="isCollapse"
      unique-opened
      router
    >
      <el-submenu
        v-for="item in $store.state.Routers"
        :key="item.path"
        :index="item.path"
        v-if="!item.hidden"
      >
        <template slot="title" >
          <i class="el-icon-location"></i>
          <span>{{ item.meta.title }}</span>
        </template>
        <div v-for="chi in item.children" :key="chi.name">
          <el-menu-item v-if="!chi.hidden" :index="item.path + '/' + chi.path">
            <i class="el-icon-location"></i>{{ chi.meta.title }}
          </el-menu-item>
        </div>
      </el-submenu>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: "MenuList",
  data() {
    return {
      isCollapse: false,
    };
  },
  created() {
    this.$bus.$on("getColl", (data) => {
      this.isCollapse = data;
    });
  },
  methods: {

  }
};
</script>

<style scoped>
.menu_wrap {
  height: 100vh;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  height: 100vh;
}
</style>
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export const routes = [
  {
    path: '/home',
    name: 'First',
    component: () => import('../views/Index.vue'),
    meta: { title: 'Home'},
    children: [
      {
        path: 'index',
        name: 'Home',
        component: () => import('../views/Home'),
        meta: { title: 'Home', roles: ['Customer'] }
      }
    ]
  },
  {
    path: '/index',
    name: 'NavigationOne',
    component: () => import('../views/Index.vue'),
    meta: { title: '导航一'},
    children: [
      {
        path: 'personnel',
        name: 'Personnel ',
        component: () => import('../views/One/Personnel.vue'),
        meta: { title: 'Personnel', roles: ['Customer'] }
      },
      {
        path: 'account',
        name: 'Account',
        component: () => import('../views/One/Account.vue'),
        meta: { title: 'Account', roles: ['Customer'] }
      },
      {
        path: 'psw',
        name: 'psw',
        component: () => import('../views/One/Password.vue'),
        meta: { title: 'psw', roles: ['Customer'] }
      }
    ]
  },
  {
    path: '/card',
    name: 'NavigationTwo',
    component: () => import('../views/Index.vue'),
    meta: { title: '导航二'},
    children: [
      {
        path: 'activity',
        name: 'Activity ',
        component: () => import('../views/Three/Activity.vue'),
        meta: { title: 'Activity', roles: ['Customer'] }
      },
      {
        path: 'Social',
        name: 'Social',
        component: () => import('../views/Three/Social.vue'),
        meta: { title: 'Social', roles: ['Customer'] }
      },
      {
        path: 'content',
        name: 'Content',
        component: () => import('../views/Three/Content.vue'),
        meta: { title: 'Content', roles: ['Customer'] }
      }
    ]
  },
  {
    path: '/two',
    name: 'NavigationThree',
    component: () => import('../views/Index.vue'),
    meta: { title: '导航三'},
    children: [
      {
        path: 'index',
        name: 'Two ',
        component: () => import('../views/Two'),
        meta: { title: 'Two', roles: ['Customer'] }
      }]
  },
  {
    path: '/404',
    name: 'Error',
    hidden: true,
    meta: { title: 'error'},
    component: () => import('../views/Error')
  }
]

export const asyncRouter = [
  // Agent3 Staff2
  {
    path: '/agent',
    component: () => import('../views/Index.vue'),
    name: 'Agent',
    meta: { title: 'Agent', roles: ['Agent','Staff']},
    children: [
      {
        path: 'one',
        name: 'agentOne',
        component: () => import('@/views/agent/One'),
        meta: { title: 'agentOne', roles: ['Agent','Staff']  }
      },
      {
        path: 'two',
        name: 'agentTwo',
        component: () => import('@/views/agent/Two'),
        meta: { title: 'agentTwo', roles: ['Agent']  }
      },
      {
        path: 'three',
        name: 'agentThree',
        component: () => import('@/views/agent/Three'),
        meta: { title: 'agentThree', roles: ['Agent','Staff']  }
      }
    ]
  },
  // Staff3
  {
    path: '/staff',
    component: () => import('../views/Index.vue'),
    name: 'Staff',
    meta: { title: 'Staff', roles: ['Staff']},
    children: [
      {
        path: 'one',
        name: 'StaffOne',
        component: () => import('@/views/Staff/One'),
        meta: { title: 'StaffOne', roles: ['Staff']  }
      },
      {
        path: 'two',
        name: 'StaffTwo',
        component: () => import('@/views/Staff/Two'),
        meta: { title: 'StaffTwo', roles: ['Staff']  }
      },
      {
        path: 'three',
        name: 'StaffThree',
        component: () => import('@/views/Staff/Three'),
        meta: { title: 'StaffThree', roles: ['Staff']  }
      }
    ]
  },
  { path: '*', redirect: '/404', hidden: true }
]

const router = new VueRouter({
  routes
})


router.beforeEach((to, from, next) =>{
  let roles = ['Staff']
  if(store.state.Routers.length) {
    console.log('yes')
    next()
  } else {
    console.log('not')
    store.dispatch('asyncGetRouter', {roles})
    .then(res =>{
      router.addRoutes(store.state.addRouters)
    })
    next({...to})
    // next()与next({ ...to })的区别:next() 放行   next('/XXX') 无限拦截
  }
})

export default router

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './module'

import router, {routes, asyncRouter} from '../router'

function hasPermission(route, roles) {
  if(route.meta && route.meta.roles) {
    return roles.some(role =>route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
  
}

/*
  递归过滤异步路由表 返回符合用户角色的路由
  @param asyncRouter 异步路由
  @param roles 用户角色
*/
function filterAsyncRouter(asyncRouter, roles) {
  let filterRouter = asyncRouter.filter(route =>{
    if(hasPermission(route, roles)) {
      if(route.children && route.children.length) {
          route.children = filterAsyncRouter(route.children, roles)
      }
      return true 
    }
    return false
  })
  return filterRouter
}

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    addRouters:  [],
    Routers: []
  },
  mutations: {
    getRouter(state, paload) {
      // console.log(paload)
      state.Routers = routes.concat(paload)
      state.addRouters = paload
      // router.addRoutes(paload)
    }
  },
  actions: {
    asyncGetRouter({ commit }, data) {
      const { roles } = data
      return new Promise(resolve =>{
        let addAsyncRouters = filterAsyncRouter(asyncRouter, roles)
        commit('getRouter', addAsyncRouters)
        resolve()
      })
    }
  }
})

到此这篇关于vue中根据用户权限动态添加路由详解的文章就介绍到这了,更多相关vue动态添加路由内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 使用vue实现一个电子签名组件的示例代码

    使用vue实现一个电子签名组件的示例代码

    这篇文章主要介绍了使用vue实现一个电子签名组件的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • vue 如何实现表单校验

    vue 如何实现表单校验

    这篇文章主要介绍的是vue 如何实现表单校验的方法,又代码详细解说,感兴趣的小伙伴可以参考下面文章的具体内容
    2021-09-09
  • Vue中import from的来源及省略后缀与加载文件夹问题

    Vue中import from的来源及省略后缀与加载文件夹问题

    这篇文章主要介绍了Vue中import from的来源--省略后缀与加载文件夹,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • 浅谈vue父子组件怎么传值

    浅谈vue父子组件怎么传值

    这篇文章主要介绍了浅谈vue父子组件怎么传值,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • Vue 中axios配置实例详解

    Vue 中axios配置实例详解

    本文通过实例代码给大家介绍了Vue axios配置,非常不错,代码简单易懂,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-07-07
  • 关于Vue在ie10下空白页的debug小结

    关于Vue在ie10下空白页的debug小结

    这篇文章主要给大家介绍了关于Vue在ie10下空白页的debug相关资料,这是最近在工作中遇到的一个问题,通过查找相关的资料终于解决了,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-05-05
  • Vue页面切换和a链接的本质区别详解

    Vue页面切换和a链接的本质区别详解

    今天小编就为大家分享一篇Vue页面切换和a链接的本质区别详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • Vue之Computed依赖收集与更新原理分析

    Vue之Computed依赖收集与更新原理分析

    这篇文章主要介绍了Vue之Computed依赖收集与更新原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • Vue3中reactive变量重新赋值无法响应的3种处理方法

    Vue3中reactive变量重新赋值无法响应的3种处理方法

    这篇文章主要给大家介绍了关于Vue3中reactive变量重新赋值无法响应的3种处理方法,在Vue3中可以使用reactive函数将一个普通对象转换为响应式对象,需要的朋友可以参考下
    2023-08-08
  • Vue3 携手 TypeScript 搭建完整项目结构

    Vue3 携手 TypeScript 搭建完整项目结构

    TypeScript 是JS的一个超级,主要提供了类型系统和对ES6的支持,使用 TypeScript 可以增加代码的可读性和可维护性,在 react 和 vue 社区中也越来越多人开始使用TypeScript,这篇文章主要介绍了Vue3 携手 TypeScript 搭建完整项目结构,需要的朋友可以参考下
    2022-04-04

最新评论