'admin-21.02.25:处理后端控制路由(页面刷新问题未处理)'

This commit is contained in:
lyt-Top 2021-02-25 00:42:24 +08:00
parent b8c6e248a7
commit 7ce8e26f0a
5 changed files with 90 additions and 135 deletions

View File

@ -39,60 +39,6 @@
"icon": "iconfonticon-quanxian"
},
"children": [
{
"path": "/limits/frontEnd",
"name": "limitsFrontEnd",
"component": "layout/routerView/parent",
"redirect": "/limits/frontEnd/page",
"meta": {
"title": "前端控制",
"isLink": "",
"isHide": false,
"isKeepAlive": true,
"isAffix": false,
"isIframe": false,
"auth": [
"admin",
"test"
]
},
"children": [
{
"path": "/limits/frontEnd/page",
"name": "limitsFrontEndPage",
"component": "limits/frontEnd/page/index",
"meta": {
"title": "页面权限",
"isLink": "",
"isHide": false,
"isKeepAlive": true,
"isAffix": false,
"isIframe": false,
"auth": [
"admin",
"test"
]
}
},
{
"path": "/limits/frontEnd/btn",
"name": "limitsFrontEndBtn",
"component": "limits/frontEnd/btn/index",
"meta": {
"title": "按钮权限",
"isLink": "",
"isHide": false,
"isKeepAlive": true,
"isAffix": false,
"isIframe": false,
"auth": [
"admin",
"test"
]
}
}
]
},
{
"path": "/limits/backEnd",
"name": "limitsBackEnd",

View File

@ -1,7 +1,7 @@
import { defineAsyncComponent } from 'vue'
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { store } from "/@/store/index.ts"
import { getSession, clearSession } from "/@/utils/storage.ts"
import { getMenuAdmin, getMenuTest } from '/@/api/menu/index.ts'
@ -452,16 +452,21 @@ const staticRoutes: Array<RouteRecordRaw> = [
meta: {
title: '没有权限'
}
},
{
}
]
// 定义404界面
const pathMatch = {
path: '/:pathMatch(.*)',
name: 'pathMatch',
redirect: '/404',
component: () => import('/@/views/error/404.vue'),
meta: {
title: '页面找不到重定向'
}
}
]
}
// 获取目录下的 .vue 全部文件,参考 viteimport.meta.glob
const dynamicViewsModules = import.meta.glob('../views/**/*.{vue,tsx}')
// 添加静态路由
const router = createRouter({
@ -470,72 +475,66 @@ const router = createRouter({
})
// 后端控制路由isRequestRoutes 为 true则开启后端控制路由
// console.log(store)
// console.log(dynamicRoutes)
// store.dispatch('setBackEndControlRoutes', 'admin')
export function getBackEndControlRoutes() {
getMenuTest().then((res: any) => {
console.log(JSON.parse(JSON.stringify(res)));
// console.log(backEndRouter(res.data))
dynamicRoutes[0].children = backEndRouter(res.data)
dynamicRoutes[0].children = res.data
console.log(dynamicRoutes)
// initAllFun()
store.dispatch('setUserInfos')
NProgress.remove()
const auth = store.state.userInfos.authPageList[0] // 模拟 admin 与 test
if (auth !== 'admin') {
getMenuAdmin().then((res: any) => {
setBackEndControlRoutesFun(res)
})
} else {
getMenuTest().then((res: any) => {
setTimeout(() => {
setBackEndControlRoutesFun(res)
}, 500)
})
}
}
// 后端控制路由,模拟执行路由初始化
export function setBackEndControlRoutesFun(res: any) {
const oldRoutes = JSON.parse(JSON.stringify(res.data))
store.dispatch('setBackEndControlRoutes', oldRoutes)
dynamicRoutes[0].children = backEndRouter(res.data)
setAddRoute() // 添加动态路由
router.addRoute(pathMatch) // 添加404界面
setFilterMenu() // 过滤权限菜单
setCacheTagsViewRoutes() // 添加 keepAlive 缓存
// console.log(router.getRoutes())
});
// window.location.href = window.location.href // 页面刷新时防止404未找到方法临时使用控制台报黄
console.log(store)
}
// export function loadView(path: string) {
// return () => import(`../views/${path}.vue`)
// }
// 后端控制路由,递归处理每一项 `component` 中的路径
// export function backEndRouter(routes: any) {
// if (!routes) return false
// return routes.map((v: any) => {
// if (v.component) v.component = () => import(`../views${v.component}.vue`)
// if (v.children) v.children = backEndRouter(v.children)
// return v
// })
// }
const dynamicViewsModules = import.meta.glob('../views/**/*.{vue,tsx}');
console.log(dynamicViewsModules)
// 后端控制路由,后端路由 component 转换
export function backEndRouter(routes: any) {
if (!routes) return;
return routes.forEach((item: any) => {
const { component } = item;
const { children } = item;
if (component) item.component = dynamicImport(dynamicViewsModules, component as string);
children && backEndRouter(children);
if (!routes) return
return routes.map((item: any) => {
const { component } = item
const { children } = item
if (component) item.component = dynamicImport(dynamicViewsModules, component as string)
children && backEndRouter(children)
return item
});
})
}
// 后端控制路由,后端路由 component 转换函数
export function dynamicImport(
dynamicViewsModules: Record<string, () => Promise<{ [key: string]: any; }>>,
dynamicViewsModules: Record<string, () => Promise<{ [key: string]: any }>>,
component: string
) {
const keys = Object.keys(dynamicViewsModules);
const keys = Object.keys(dynamicViewsModules)
const matchKeys = keys.filter((key) => {
const k = key.replace('../views', '');
return k.startsWith(`${component}`) || k.startsWith(`/${component}`);
});
console.log(matchKeys)
const k = key.replace('../views', '')
return k.startsWith(`${component}`) || k.startsWith(`/${component}`)
})
if (matchKeys?.length === 1) {
const matchKey = matchKeys[0];
return dynamicViewsModules[matchKey];
const matchKey = matchKeys[0]
return dynamicViewsModules[matchKey]
}
if (matchKeys?.length > 1) {
console.warn('Please do not create');
return false;
console.warn('Do not create files that do not end with. Vue')
return false
}
}
@ -607,7 +606,7 @@ export function setFilterMenuFun(routes: any, auth: any) {
export function setFilterRoute() {
let filterRoute: any = []
formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes))[0].children.map((route: any) => {
route.meta.auth.map((metaAuth: any) => {
if (route.meta.auth) route.meta.auth.map((metaAuth: any) => {
store.state.userInfos.authPageList.map((auth: any) => {
if (metaAuth === auth) filterRoute.push({ ...route })
})
@ -640,20 +639,17 @@ export function resetRoute() {
// 初始化方法,防止刷新时丢失
export function initAllFun() {
const token = getSession('token')
if (!token) return false
setTimeout(() => {
store.dispatch('setUserInfos')
store.dispatch('setUserInfos') // 触发初始化用户信息
setAddRoute() // 添加动态路由
router.addRoute(pathMatch) // 添加404界面
setFilterMenu() // 过滤权限菜单
setCacheTagsViewRoutes() // 添加 keepAlive 缓存
}, 1000)
}
// 初始化方法执行
if (!store.state.themeConfig.isRequestRoutes) initAllFun()
if (!store.state.themeConfig.isRequestRoutes && getSession('token')) initAllFun()
// 后端控制路由isRequestRoutes 为 true则开启后端控制路由
if (store.state.themeConfig.isRequestRoutes) getBackEndControlRoutes()
if (store.state.themeConfig.isRequestRoutes && getSession('token')) getBackEndControlRoutes()
// 路由加载前
router.beforeEach((to, from, next) => {
@ -674,7 +670,7 @@ router.beforeEach((to, from, next) => {
next('/home')
NProgress.done()
} else {
next();
next()
}
}
})

View File

@ -48,7 +48,8 @@ export interface RootStateTypes {
routes: Array<object>,
keepAliveNames: Array<string>,
tagsViewRoutes: Array<object>,
userInfos: object
userInfos: object,
requestOldRoutes: Array<object>,
}
export const key: InjectionKey<Store<RootStateTypes>> = Symbol()
@ -59,7 +60,8 @@ export const store = createStore<RootStateTypes>({
routes: [],
keepAliveNames: [],
tagsViewRoutes: [],
userInfos: {}
userInfos: {},
requestOldRoutes: []
},
mutations: {
// 设置布局配置
@ -82,6 +84,10 @@ export const store = createStore<RootStateTypes>({
getUserInfos(state: any, data: object) {
state.userInfos = data
},
// 后端控制路由
getBackEndControlRoutes(state: any, data: object) {
state.requestOldRoutes = data
},
},
actions: {
// 设置布局配置
@ -109,10 +115,8 @@ export const store = createStore<RootStateTypes>({
}
},
// 后端控制路由
async setBackEndControlRoutes({ commit }, query: string) {
if (query === 'admin') {
} else { }
setBackEndControlRoutes({ commit }, routes: Array<string>) {
commit('getBackEndControlRoutes', routes)
}
}
})

View File

@ -39,5 +39,5 @@ export default {
animation: 'slideRight',
columnsAsideStyle: 'columnsRound',
layout: 'defaults',
isRequestRoutes: false
isRequestRoutes: true
}

View File

@ -39,6 +39,7 @@ import {
setAddRoute,
setFilterMenu,
setCacheTagsViewRoutes,
getBackEndControlRoutes,
} from "/@/router/index.ts";
import { useStore } from "/@/store/index.ts";
import { setSession } from "/@/utils/storage.ts";
@ -100,11 +101,19 @@ export default defineComponent({
authPageList: defaultAuthPageList,
authBtnList: defaultAuthBtnList,
};
// token
setSession("token", Math.random().toString(36).substr(0));
//
setSession("userInfo", userInfos);
store.dispatch("setUserInfos", userInfos); // (vuex)
initAllFun(); //
// 1(vuex)
store.dispatch("setUserInfos", userInfos);
// 2
if (store.state.themeConfig.isRequestRoutes) initAllFun();
// isRequestRoutes true
else getBackEndControlRoutes();
//
router.push("/");
//
setTimeout(() => {
ElMessage.success(`${currentTimeInfo},欢迎回来!`);
}, 300);