diff --git a/src/main.ts b/src/main.ts index ee047f61b..f87a54416 100644 --- a/src/main.ts +++ b/src/main.ts @@ -9,7 +9,7 @@ import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' // 导入公共样式 -import "./assets/index.css" +import './assets/index.css' const app = createApp(App) diff --git a/src/router/index.ts b/src/router/index.ts index 8ee8ab1c8..5931e7433 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -1,6 +1,6 @@ -import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' -import Home from '../views/home.vue' -import { setToken, getToken } from "../utils/token" +import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router" +import Home from "../views/home.vue" +import { storageSession } from "../utils/storage" const routes: Array = [ { @@ -34,8 +34,7 @@ const router = createRouter({ const whiteList = ["/login", "/register"] router.beforeEach((to, _from, next) => { - const token = getToken() - whiteList.indexOf(to.path) !== -1 || token ? next() : next("/login") // 全部重定向到登录页 + whiteList.indexOf(to.path) !== -1 || storageSession.getItem("Token") ? next() : next("/login") // 全部重定向到登录页 }) export default router diff --git a/src/utils/storage/index.ts b/src/utils/storage/index.ts new file mode 100644 index 000000000..7da3cd372 --- /dev/null +++ b/src/utils/storage/index.ts @@ -0,0 +1,42 @@ +interface ProxyStorage { + getItem(key: string): any + setItem(Key: string, value: string): void + removeItem(key: string): void +} + +//sessionStorage operate +class sessionStorageProxy implements ProxyStorage { + + protected storage: ProxyStorage + + constructor(storageModel: ProxyStorage) { + this.storage = storageModel + } + + // 存 + public setItem(key: string, value: string): void { + this.storage.setItem(key, JSON.stringify(value)) + } + + // 取 + public getItem(key: string): any { + return JSON.parse(this.storage.getItem(key)) || null + } + + // 删 + public removeItem(key: string): void { + this.storage.removeItem(key) + } + +} + +//localStorage operate +class localStorageProxy extends sessionStorageProxy implements ProxyStorage { + constructor(localStorage: ProxyStorage) { + super(localStorage) + } +} + +export const storageSession = new sessionStorageProxy(sessionStorage) + +export const storageLocal = new localStorageProxy(localStorage) \ No newline at end of file diff --git a/src/utils/token.ts b/src/utils/token.ts deleted file mode 100644 index 2c922b610..000000000 --- a/src/utils/token.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 处理token的工具 - */ - -// 存 -export function setToken(token: string): void { - token && sessionStorage.setItem("Token", token) -} - -// 取 -export function getToken(): string { - let token = sessionStorage.getItem("Token") && JSON.parse(sessionStorage.getItem("Token") || "") - return token -} - -// 删 -export function delToken(): void { - sessionStorage.removeItem("Token") -} \ No newline at end of file