xyh 2 лет назад
Родитель
Сommit
21e3ecdb2f
6 измененных файлов с 73 добавлено и 1 удалено
  1. 15 0
      src/routes/index.ts
  2. 5 0
      src/routes/name.ts
  3. 1 0
      src/stores/index.ts
  4. 2 1
      src/stores/tab.ts
  5. 47 0
      src/stores/user.ts
  6. 3 0
      src/utils/constants.ts

+ 15 - 0
src/routes/index.ts

@@ -13,6 +13,7 @@ import {
 } from './name';
 import Home from '@pages/home/index.vue';
 import Login from '@pages/login/index.vue';
+import {storeToRefs, useUserStore} from '@stores';
 
 const routes: RouteRecordRaw[] = [
   {
@@ -47,4 +48,18 @@ export const router = createRouter({
   routes,
 });
 
+router.beforeEach(function(to) {
+  const {name} = to;
+  if (name) {
+    const userStore = useUserStore();
+    const {user} = storeToRefs(userStore);
+
+    if (!user.value.token) {
+      // 判断是否登录
+      const matchList = [LOGIN_NAME, REGISTER_NAME];
+      if (!matchList.includes(name as symbol)) return LOGIN_PATH;
+    }
+  }
+});
+
 export * from './name';

+ 5 - 0
src/routes/name.ts

@@ -1,3 +1,8 @@
+/**
+ * 路由名称对应所在路由的main组件名称
+ * 为了处理keepalive只保存tab中显示的内容
+ * 详情查 pages/home/index.vue
+ */
 export const RouteNameMap = new Map();
 
 /** 主体内容 */

+ 1 - 0
src/stores/index.ts

@@ -1,2 +1,3 @@
 export * from './tab';
+export * from './user';
 export {storeToRefs} from 'pinia';

+ 2 - 1
src/stores/tab.ts

@@ -1,5 +1,6 @@
 import {defineStore} from 'pinia';
 import {klona} from 'klona/json';
+import {MAIN_PATH} from '@routes';
 
 type State = {
   activeKey: string;
@@ -27,7 +28,7 @@ type Action = {
 
 const defaultTab: State['tabList'][0] = {
   key: '-1',
-  url: '/',
+  url: MAIN_PATH,
   label: '首页',
   pid: '0',
 };

+ 47 - 0
src/stores/user.ts

@@ -0,0 +1,47 @@
+import {USER_STORAGE_KEY} from '@utils';
+import {defineStore} from 'pinia';
+
+type State = {
+  user: {
+    id: number,
+    realName: string,
+    token: string,
+    userName: string,
+    department: string,
+    role: string,
+  }
+};
+
+type Action = {
+  init: (state: State['user']) => void;
+};
+
+export const useUserStore = defineStore<string, State, any, Action>(
+  'userStore',
+  {
+    state() {
+      const userLocalStorage = localStorage.getItem(USER_STORAGE_KEY);
+      const user: State['user'] = {
+        id: 0,
+        realName: '',
+        token: '',
+        userName: '',
+        department: '',
+        role: '',
+      };
+      if (userLocalStorage) {
+        Object.assign(
+          user,
+          JSON.parse(userLocalStorage) as State['user'],
+        );
+      }
+
+      return {user};
+    },
+    actions: {
+      init(state) {
+        this.user = state;
+      },
+    },
+  },
+);

+ 3 - 0
src/utils/constants.ts

@@ -3,3 +3,6 @@ export const NETWORK_URL
   = process.env.NODE_ENV === 'development'
     ? 'http://jsonplaceholder.typicode.com'
     : 'http://10.2.111.91:9560';
+
+/** 用户存储Key */
+export const USER_STORAGE_KEY = 'userStore';