vue3路由+权限

原文地址:vue3路由+权限 - 简书

  1. router.ts

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from '@/views/layout/layout.vue';
import loginLayout from '@/views/layout/loginLayout.vue';
const routes: Array = [
 {
   path: '/',
   redirect: '/login',
 },
 {
   path: '/login',
   name: 'Login',
   component: () => import('@/views/login/login.vue'),
   meta: { title: '登录', icon: '', parent: { name: '' } }
 },
 {
   path: '/home',
   name: 'Home',
   component: () => import('@/views/home/home.vue'),
   // hidden: true,
   meta: { title: '首页', icon: '', parent: { name: '' }}
 },
 {
   path: '/errPage',
   name: 'ErrPage',
   component: () => import('@/views/404.vue'),
 },
]

/**
* @description: 路由表配置 控制权限的路由最好不要设置 redirect,通过权限逻辑会自动定向
* @hidden {*} 是否在菜单隐藏路由 true 隐藏
* @noAuth {*} //不需要控制权限的添加 路由表添加noAuth:true字段
* @parent {*} //meta 标签的title和parent字段必传,为了菜单选中和张开使用. 因为useRoute()去掉了parent属性
*/
interface AsyncRoutesMap{
 path:string,
 name?:string,
 meta?:{
   title:string,
   parent:{
     name:string
   },
   [props: string]: any
 },
 [props:string]:any
}
export const asyncRoutesMap: Array = [
 {
   path: '/dashboard',
   name: 'Dashboard',
   component: Layout,
   // redirect:{name:'Work'},
   meta: { title: '工作台', icon: 'home',parent:{name:''} },
   hidden: false,
   children: [
     {
       path: 'work',
       name: 'Work',
       component: () => import('@/views/work/index.vue'),
       redirect: { name: 'WorkList' },
       meta: { title: '业务', icon: '', parent: { name: 'Dashboard' } },
       hidden: false,
       children: [
         {
           path: 'workList',
           name: 'WorkList',
           component: () => import('@/views/work/list.vue'),
           meta: { title: '业务列表', noAuth: true, parent: { name: 'Work' }},
           hidden: true,
         },
         {
           path: 'detail',
           name: 'Detail',
           component: () => import('@/views/work/detail.vue'),
           meta: { title: '业务详情', noAuth: true ,parent: { name: 'Work' }},
           hidden: true,
         },
       ]
     },
   ]
 },
 {
   path: '/hoy',
   name: 'Hoy',
   component: Layout,
   // redirect:{name:'MyHoy'},
   meta: { title: 'Hoy', icon: 'home', parent: { name: '' } },
   hidden: false,
   children: [
     {
       path: 'myHoy',
       name: 'MyHoy',
       component: () => import('@/views/myHoy/index.vue'),
       meta: { title: '我的Hoy', icon: '', parent: { name: 'Hoy' } },
       hidden: false,
     },
   ]
 },
 {
   path: '/:pathMatch(.*)*',
   redirect: { name:'ErrPage'},
   hidden: true
 }
]

const router = createRouter({
 history: createWebHistory(process.env.URL),
 routes
})

export default router


  1. permission.ts

/**
 * @Author: DDY
 * @Date: 2021-09-04 20:42:08
 * @description: 权限路由守卫
 */
import router, { asyncRoutesMap } from './router/index';
import store from './store';
import { message } from 'ant-design-vue';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login','/errPage'] // 不重定向白名单
router.beforeEach((to,from,next) => {
    NProgress.start()
    if (whiteList.indexOf(to.path) !== -1) {
        next();
    } else {
        const token = store.getters['token'];
        if (token){
            let asyncRouets = store.getters.asyncRoutes;
            if (asyncRouets.length){
                //处理过有权限的路由信息
                next();
            }else{
                store.dispatch('User/getUserInfo').then(res => {
                    let a:any = store.state
                    let permissions_url = a.User.asyncRoutesName
                    //根据权限name处理路由表
                    const addRoutes:any = filterAsyncRouter(permissions_url, asyncRoutesMap)
                    addRoutes.map((item:any)=>{
                        router.addRoute(item) // 动态添加可访问路由表
                    })
                    store.commit('User/SET_ASYNC_ROUTES', addRoutes)
                    if (addRoutes.length){
                        next({ ...to, replace: true });
                    }else{
                        message.error('您没有查看页面的权限!')
                        next('/')
                    }
                }).catch((err) => {
                    store.dispatch('User/logOut').then(() => {
                        message.error(err || 'Verification failed, please login again')
                        next('/')
                    })
                })
            }
        }else{
            next("/");
        }
    }
})
function resolveRoute() {
    //跳转对应的地址
    let env = process.env.NODE_ENV;
    let hostName = location.hostname;
    NProgress.done()
}

/**
 * 通过meta.url判断是否与当前用户权限匹配
 * @param {*} permissions_url  接口返回的权限 [{name:'xxx'}]
 * @param {*} route  某条路由信息
 */
export const hasPermission=function(permissions_url: any[], route:any) {
    if (route.name) {
        return permissions_url.some(item => {
            return route.name == item.name
        })
    } else {
        return true
    }
}
/**
 * @description: 用户所拥有的权限AsyncRouter 路由表
 * @param {*} permissions_url  接口返回的权限 [{name:'xxx'}]
 * @param {*} asyncRouterMap  路由表所有的异步路由 []
 * @return {*}  用户所拥有的权限AsyncRouter 路由表
 */
export const filterAsyncRouter = function (permissions_url: any[], asyncRouterMap: any[]) {
    const accessedRouters = asyncRouterMap.filter(route => { //返回符合条件的路由
        if (route.meta && route.meta.noAuth) {  //不需要控制权限的添加 路由表添加noAuth:true字段
            return true;
        }
        if (hasPermission(permissions_url, route)) { //符合条件的
            if (route.children && route.children.length) {
                route.children=filterAsyncRouter(permissions_url, route.children);
            }
            return true;
        }
        return false;
    });
    return accessedRouters
}
router.onError((handler: any) => {
    console.log("error:", handler);
    NProgress.done()
});
router.afterEach(() => {
    NProgress.done()
})

  1. store>modules>user.ts

    /**
     * @description: 设置用户拥有权限的路由配置列表
     */
    SET_ASYNC_ROUTES: (state, routesInfo) => {
        state.asyncRoutes =  routesInfo;
    },
    /**
     * @description: 设置用户拥有权限的路由名称
     */    
    SET_ASYNC_ROUTES_NAME: (state, routesInfo) => {
        state.asyncRoutesName =  routesInfo;
    },



作者:小米和豆豆
链接:https://www.jianshu.com/p/4b6a0ded25da
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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