- 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<RouteRecordRaw> = [
{
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: 路由表配置 控制權(quán)限的路由最好不要設(shè)置 redirect,通過權(quán)限邏輯會自動定向
* @hidden {*} 是否在菜單隱藏路由 true 隱藏
* @noAuth {*} //不需要控制權(quán)限的添加 路由表添加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<AsyncRoutesMap> = [
{
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: '業(yè)務(wù)', icon: '', parent: { name: 'Dashboard' } },
hidden: false,
children: [
{
path: 'workList',
name: 'WorkList',
component: () => import('@/views/work/list.vue'),
meta: { title: '業(yè)務(wù)列表', noAuth: true, parent: { name: 'Work' }},
hidden: true,
},
{
path: 'detail',
name: 'Detail',
component: () => import('@/views/work/detail.vue'),
meta: { title: '業(yè)務(wù)詳情', 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
- permission.ts
/**
* @Author: DDY
* @Date: 2021-09-04 20:42:08
* @description: 權(quán)限路由守衛(wèi)
*/
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){
//處理過有權(quán)限的路由信息
next();
}else{
store.dispatch('User/getUserInfo').then(res => {
let a:any = store.state
let permissions_url = a.User.asyncRoutesName
//根據(jù)權(quán)限name處理路由表
const addRoutes:any = filterAsyncRouter(permissions_url, asyncRoutesMap)
addRoutes.map((item:any)=>{
router.addRoute(item) // 動態(tài)添加可訪問路由表
})
store.commit('User/SET_ASYNC_ROUTES', addRoutes)
if (addRoutes.length){
next({ ...to, replace: true });
}else{
message.error('您沒有查看頁面的權(quán)限!')
next('/')
}
}).catch((err) => {
store.dispatch('User/logOut').then(() => {
message.error(err || 'Verification failed, please login again')
next('/')
})
})
}
}else{
next("/");
}
}
})
function resolveRoute() {
//跳轉(zhuǎn)對應(yīng)的地址
let env = process.env.NODE_ENV;
let hostName = location.hostname;
NProgress.done()
}
/**
* 通過meta.url判斷是否與當前用戶權(quán)限匹配
* @param {*} permissions_url 接口返回的權(quán)限 [{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: 用戶所擁有的權(quán)限AsyncRouter 路由表
* @param {*} permissions_url 接口返回的權(quán)限 [{name:'xxx'}]
* @param {*} asyncRouterMap 路由表所有的異步路由 []
* @return {*} 用戶所擁有的權(quán)限AsyncRouter 路由表
*/
export const filterAsyncRouter = function (permissions_url: any[], asyncRouterMap: any[]) {
const accessedRouters = asyncRouterMap.filter(route => { //返回符合條件的路由
if (route.meta && route.meta.noAuth) { //不需要控制權(quán)限的添加 路由表添加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()
})
- store>modules>user.ts
/**
* @description: 設(shè)置用戶擁有權(quán)限的路由配置列表
*/
SET_ASYNC_ROUTES: (state, routesInfo) => {
state.asyncRoutes = routesInfo;
},
/**
* @description: 設(shè)置用戶擁有權(quán)限的路由名稱
*/
SET_ASYNC_ROUTES_NAME: (state, routesInfo) => {
state.asyncRoutesName = routesInfo;
},