From 7ce8e26f0a4661274385331b8bc4b608ba5129eb Mon Sep 17 00:00:00 2001 From: lyt-Top <1105290566@qq.com> Date: Thu, 25 Feb 2021 00:42:24 +0800 Subject: [PATCH] =?UTF-8?q?'admin-21.02.25:=E5=A4=84=E7=90=86=E5=90=8E?= =?UTF-8?q?=E7=AB=AF=E6=8E=A7=E5=88=B6=E8=B7=AF=E7=94=B1(=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2=E5=88=B7=E6=96=B0=E9=97=AE=E9=A2=98=E6=9C=AA=E5=A4=84?= =?UTF-8?q?=E7=90=86)'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/menu/testMenu.json | 54 ---------- src/router/index.ts | 140 +++++++++++++------------- src/store/index.ts | 16 +-- src/utils/themeConfig.ts | 2 +- src/views/login/component/account.vue | 13 ++- 5 files changed, 90 insertions(+), 135 deletions(-) diff --git a/src/api/menu/testMenu.json b/src/api/menu/testMenu.json index bf17dca..3a461ef 100644 --- a/src/api/menu/testMenu.json +++ b/src/api/menu/testMenu.json @@ -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", diff --git a/src/router/index.ts b/src/router/index.ts index 65cccf6..bbfcc59 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -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,17 +452,22 @@ const staticRoutes: Array = [ meta: { title: '没有权限' } - }, - { - path: '/:pathMatch(.*)', - name: 'pathMatch', - redirect: '/404', - meta: { - title: '页面找不到重定向' - } } ] +// 定义404界面 +const pathMatch = { + path: '/:pathMatch(.*)', + name: 'pathMatch', + component: () => import('/@/views/error/404.vue'), + meta: { + title: '页面找不到重定向' + } +} + +// 获取目录下的 .vue 全部文件,参考 vite:import.meta.glob +const dynamicViewsModules = import.meta.glob('../views/**/*.{vue,tsx}') + // 添加静态路由 const router = createRouter({ history: createWebHashHistory(), @@ -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') - setAddRoute() // 添加动态路由 - setFilterMenu() // 过滤权限菜单 - setCacheTagsViewRoutes() // 添加 keepAlive 缓存 - // console.log(router.getRoutes()) - }); + 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 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) - +// 后端控制路由,模拟执行路由初始化 +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 缓存 + // window.location.href = window.location.href // 页面刷新时,防止404(未找到方法,临时使用,控制台报黄) + console.log(store) +} +// 后端控制路由,后端路由 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 Promise<{ [key: string]: any; }>>, + dynamicViewsModules: Record 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') - setAddRoute() // 添加动态路由 - setFilterMenu() // 过滤权限菜单 - setCacheTagsViewRoutes() // 添加 keepAlive 缓存 - }, 1000) + store.dispatch('setUserInfos') // 触发初始化用户信息 + setAddRoute() // 添加动态路由 + router.addRoute(pathMatch) // 添加404界面 + setFilterMenu() // 过滤权限菜单 + setCacheTagsViewRoutes() // 添加 keepAlive 缓存 } // 初始化方法执行 -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() } } }) diff --git a/src/store/index.ts b/src/store/index.ts index fd85952..ab71d81 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -48,7 +48,8 @@ export interface RootStateTypes { routes: Array, keepAliveNames: Array, tagsViewRoutes: Array, - userInfos: object + userInfos: object, + requestOldRoutes: Array, } export const key: InjectionKey> = Symbol() @@ -59,7 +60,8 @@ export const store = createStore({ routes: [], keepAliveNames: [], tagsViewRoutes: [], - userInfos: {} + userInfos: {}, + requestOldRoutes: [] }, mutations: { // 设置布局配置 @@ -82,6 +84,10 @@ export const store = createStore({ 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({ } }, // 后端控制路由 - async setBackEndControlRoutes({ commit }, query: string) { - if (query === 'admin') { - - } else { } + setBackEndControlRoutes({ commit }, routes: Array) { + commit('getBackEndControlRoutes', routes) } } }) diff --git a/src/utils/themeConfig.ts b/src/utils/themeConfig.ts index 1493029..8ece3e4 100644 --- a/src/utils/themeConfig.ts +++ b/src/utils/themeConfig.ts @@ -39,5 +39,5 @@ export default { animation: 'slideRight', columnsAsideStyle: 'columnsRound', layout: 'defaults', - isRequestRoutes: false + isRequestRoutes: true } \ No newline at end of file diff --git a/src/views/login/component/account.vue b/src/views/login/component/account.vue index 956e88a..49e842c 100644 --- a/src/views/login/component/account.vue +++ b/src/views/login/component/account.vue @@ -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);