fix
13404089107
2 天以前 a90bcdf047a8baf02aeec81221aeeb49db523cde
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
import Vue from 'vue'
import Router from 'vue-router'
import routes from './router'
import store from '@/store' // 导入 Vuex store
 
const changePush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return changePush.call(this, location).catch((err) => err);
};
Vue.use(Router);
 
const createRouter = () => new Router({
  mode: 'hash', // require service support
  scrollBehavior: () => ({
    y: 0
  }),
  routes
})
const router = createRouter()
// 路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token
  const permissions = store.state.permissions || []
  
  if (!token && to.path != '/') {
    // 如果没有 token 并且不是去登录页,重定向到登录页
    next('/')
  } else if (token && to.path === '/') {
    // 如果有 token 并且要去登录页,重定向到首页
    next('/home')
  } else {
    // 检查路由权限
    if (to.meta && to.meta.menuId) {
      // 如果路由有menuId,检查是否有权限访问
      if (permissions.length === 0) {
        // 如果权限数组为空,说明是刚登录,还未获取权限,允许访问
        next()
      } else if (permissions.includes(to.meta.menuId)) {
        // 有权限,允许访问
        next()
      } else {
        // 无权限,重定向到404或首页
        next('/404')
      }
    } else {
      // 路由没有menuId,直接放行
      next()
    }
    
    // 清理 localStorage
    localStorage.removeItem('registerForm')
  }
})
 
export default router