wanshenmean
2026-02-09 ae9517420d848e215a9eb807270d5ef6fbe92ae9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import type { Router } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
 
NProgress.configure({ showSpinner: false });
 
export function setupRouterGuard(router: Router) {
  router.beforeEach((to, from, next) => {
    NProgress.start();
 
    const authStore = useAuthStore();
    const requiresAuth = to.meta.requiresAuth !== false;
 
    if (requiresAuth && !authStore.isLoggedIn) {
      // 需要认证但未登录,跳转到登录页
      next({ path: '/login', query: { redirect: to.fullPath } });
    } else if (to.path === '/login' && authStore.isLoggedIn) {
      // 已登录访问登录页,跳转到首页
      next({ path: '/' });
    } else {
      next();
    }
  });
 
  router.afterEach(() => {
    NProgress.done();
  });
}