Procházet zdrojové kódy

解决登录状态保持问题

skyline před 1 měsícem
rodič
revize
64cf534e5a

+ 3 - 2
haha-admin-mp/src/App.vue

@@ -1,5 +1,6 @@
 <script setup lang="ts">
 import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
+import { isLoggedIn } from "@/utils/auth";
 
 onLaunch((options: any) => {
   console.log("App Launch", options);
@@ -9,6 +10,7 @@ onLaunch((options: any) => {
 
 onShow(() => {
   console.log("App Show");
+  checkLoginStatus();
 });
 
 onHide(() => {
@@ -16,12 +18,11 @@ onHide(() => {
 });
 
 const checkLoginStatus = () => {
-  const token = uni.getStorageSync('admin_token');
   const pages = getCurrentPages();
   const currentPage = pages[pages.length - 1];
   const currentPath = currentPage ? currentPage.route : '';
 
-  if (!token && currentPath !== 'pages/login/login') {
+  if (!isLoggedIn() && currentPath !== 'pages/login/login') {
     console.log('未登录,跳转到登录页');
     uni.reLaunch({
       url: '/pages/login/login'

+ 8 - 1
haha-admin-mp/src/pages/login/login.vue

@@ -67,8 +67,9 @@
 </template>
 
 <script setup lang="ts">
-import { ref, reactive } from 'vue';
+import { ref, reactive, onMounted } from 'vue';
 import { login } from '@/api/auth';
+import { isLoggedIn } from '@/utils/auth';
 
 const formData = reactive({
   username: '',
@@ -78,6 +79,12 @@ const formData = reactive({
 const showPassword = ref(false);
 const loading = ref(false);
 
+onMounted(() => {
+  if (isLoggedIn()) {
+    uni.switchTab({ url: '/pages/index/index' });
+  }
+});
+
 const handleLogin = async () => {
   if (!formData.username) {
     uni.showToast({ title: '请输入用户名', icon: 'none' });

+ 3 - 3
haha-admin-mp/src/utils/request.ts

@@ -2,7 +2,7 @@
  * HTTP请求封装
  */
 
-import { getToken } from './auth';
+import { getToken, clearAuth } from './auth';
 import { API_BASE_URL } from './config';
 
 interface RequestOptions {
@@ -52,8 +52,8 @@ export function request<T = any>(options: RequestOptions): Promise<T> {
         if (response.code === 200) {
           resolve(response.data);
         } else if (response.code === 401) {
-          // Token过期,跳转登录
-          uni.removeStorageSync('admin_token');
+          // Token过期,清除登录状态并跳转登录
+          clearAuth();
           uni.reLaunch({ url: '/pages/login/login' });
           reject(new Error('登录已过期'));
         } else {