Procházet zdrojové kódy

feat:改变路由表实现方式

张涛 před 1 rokem
rodič
revize
10461b939f

+ 2 - 2
src/base/store/use-current-user.js

@@ -69,7 +69,7 @@ export const useCurrentUserStore = defineStore('current_user', {
       } = await QueyrRoutesList();
       if (code === 200) {
         // 将 setItem 包装在一个 Promise 中并等待完成
-        await new Promise((resolve, reject) => {
+        return new Promise((resolve, reject) => {
           try {
             localST_RoutesList.setItem(JSON.stringify(routers));
             resolve();
@@ -87,7 +87,7 @@ export const useCurrentUserStore = defineStore('current_user', {
         data: { permissions, dept, roles }
       } = await QueyrUserInfo();
       if (code === 200) {
-        await new Promise((resolve, reject) => {
+        return new Promise((resolve, reject) => {
           try {
             localST_UserInfo.setItem(JSON.stringify({ permissions, dept, roles }));
             resolve();

+ 2 - 0
src/modules/login/FormItem.vue

@@ -84,7 +84,9 @@ const handleSubmit = (data) => {
         await userStore.getRoutesList();
         // 登录成功后,获取用户权限
         await userStore.getUserInfo();
+
         router.push({ path: '/' });
+
       })
       .catch((err) => {
         $message.error(err);

+ 24 - 8
src/router/guard.js

@@ -1,23 +1,39 @@
 import router from './index';
 import { kuky_Authorization } from '../base/storage';
-import { accessFlatRoutes } from '../utils/permission';
+import { initializeRoutes } from '../utils/permission';
 
 /** 免验证白名单 */
 const whiteList = ['/login', '/reg', '/noPer'];
 
-// 导入所需的模块
-router.beforeEach((to, from, next) => {
+/** 是否已经生成过路由表 */
+let hasRouteFlag = false;
+export const resetHasRouteFlag = () => {
+  hasRouteFlag = false;
+};
+// 扁平路由表
+let flatRoutes = [];
+
+router.beforeEach(async (to, from, next) => {
   const isAuthorized = kuky_Authorization.get(); // 获取用户授权状态
   const isLoginPage = to.path === '/login'; // 判断目标路径是否为登录页
   const isInWhiteList = whiteList.includes(to.path); // 检查目标路径是否在白名单中
-  const hasAccess = accessFlatRoutes.some((route) => route.path == to.path);
+
   // 用户已授权的情况
   if (isAuthorized) {
-    if (isLoginPage) {
+    if (!hasRouteFlag) {
+      const { formattedRoutes, accessFlatRoutes } = await initializeRoutes();
+      formattedRoutes.forEach((route) => {
+        if (route.path && route.component) {
+          router.addRoute(route); // 动态添加可访问路由表
+        }
+      });
+      flatRoutes = accessFlatRoutes;
+      hasRouteFlag = true;
+      next({ ...to, replace: true });
+    } else if (isLoginPage) {
       next('/');
-    } else if (!hasAccess && !isInWhiteList) {
-      // 如果用户无访问权限且不在白名单中
-      next('/noPer'); // 重定向到无权限页面
+    } else if (!flatRoutes.some((route) => route.path == to.path) && !isInWhiteList) {
+      next('/noPer'); // 如果用户无访问权限且不在白名单中,重定向到无权限页面
     } else {
       next(); // 其他情况,正常访问
     }

+ 1 - 2
src/router/index.js

@@ -1,10 +1,9 @@
 import { createRouter, createWebHashHistory } from 'vue-router';
 import { systemRoutes } from './route';
-import { accessRoutes } from '../utils/permission';
 
 const router = createRouter({
   history: createWebHashHistory(),
-  routes: [...systemRoutes, ...accessRoutes],
+  routes: [...systemRoutes],
   scrollBehavior: () => ({ left: 0, top: 0 })
 });
 

+ 12 - 9
src/utils/permission.js

@@ -79,13 +79,16 @@ export const flattenRoutes = (routes) => {
 
 // 获取有权限的路由
 let routesList = [];
-try {
-  routesList = JSON.parse(localST_RoutesList.getItem());
-} catch (error) {
-  console.error('路由解析错误:', error);
-}
+let formattedRoutes = [];
+let accessFlatRoutes = [];
 
-const formattedRoutes = formatRoutes(routesList);
-export const accessRoutes = formattedRoutes;
-
-export const accessFlatRoutes = flattenRoutes(accessRoutes);
+export const initializeRoutes = () => {
+  try {
+    routesList = JSON.parse(localST_RoutesList.getItem());
+  } catch (error) {
+    console.error('路由解析错误:', error);
+  }
+  formattedRoutes = formatRoutes(routesList);
+  accessFlatRoutes = flattenRoutes(formattedRoutes);
+  return { formattedRoutes, accessFlatRoutes };
+};

+ 5 - 9
src/views/common/header-btns/ModalLogout.vue

@@ -1,13 +1,6 @@
 <template>
-  <a-modal
-    width="420px"
-    :visible="showModal"
-    @ok="handleOk"
-    @cancel="handleCancel"
-    :okText="$t('login.okBtn')"
-    :cancelText="$t('login.cancelBtn')"
-    unmountOnClose
-  >
+  <a-modal width="420px" :visible="showModal" @ok="handleOk" @cancel="handleCancel" :okText="$t('login.okBtn')"
+    :cancelText="$t('login.cancelBtn')" unmountOnClose>
     <template #title><icon-exclamation-circle-fill class="tips-icon" /> {{ $t('login.tip') }} </template>
     <div>{{ $t('login.okText') }}</div>
   </a-modal>
@@ -17,6 +10,7 @@
 import { computed } from 'vue';
 import { useRouter } from 'vue-router';
 import { kuky_Authorization } from '../../../base/storage';
+import { resetHasRouteFlag } from '../../../router/guard';
 const props = defineProps({
   visible: {
     type: Boolean,
@@ -29,7 +23,9 @@ const showModal = computed(() => props.visible);
 
 const handleOk = () => {
   kuky_Authorization.remove();
+
   // 重置路由守卫标志位
+  resetHasRouteFlag();
   router.push({ path: '/login', replace: true });
   emit('update:visible', false);
 };