zhuoyuan.wang
2024-06-19 15ebe96f28cadec6a726c5324593a40bbf56205f
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import router from './index.js';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {auth} from '@/plugins';
import {isHttp} from '@/utils/validate';
import {useUserStore, useSettingStore, useMenuStore} from '@/store/modules';
 
NProgress.configure({showSpinner: false});
 
const whiteList = ['/login'];
 
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  /**
   * 在免登录白名单,直接进入
   */
  if (whiteList.indexOf(to.path) !== -1) {
    next();
    return;
  }
 
  const token = auth.getToken();
 
  /**
   * 否则全部重定向到登录页
   */
  if (!token) {
    next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    NProgress.done();
    return;
  }
 
  if (token) {
    /**
     * 动态修改标题
     */
    to.meta.title && useSettingStore().setTitle(to.meta.title);
 
    if (to.path === '/login' || to.path === '/') {
      next({path: '/index'});
      NProgress.done();
      return;
    }
 
    if (useUserStore().user === null) {
      const [accessRoutes] = await Promise.all(
        [
          useMenuStore().getMenu(),
          useUserStore().getUser()
        ]
      );
      accessRoutes.forEach(route => {
        if (!isHttp(route.path)) {
          /**
           * 动态添加可访问路由表
           */
          router.addRoute(route);
        }
      });
      /**
       * hack方法 确保addRoutes已完成
       */
      next({...to, replace: true});
      return;
    }
 
    next();
  }
})
 
router.afterEach(() => {
  NProgress.done()
})