index.js
2.24 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Login from '@/views/Login'
// import { utils } from 'glsx-common'
// import { constants } from '@/common'
// import Home from '@/views/Home'
import E404 from '@/views/404'
// import Layout from '@/views/Layout'
Vue.use(VueRouter)
const Path = Object.freeze({
LOGIN: '/login',
E404: '/404'
})
// 路由
let constantRoutes = [
{
path: Path.LOGIN,
name: 'login',
component: Login,
meta: { isBase: true, title: '登录' }
},
{
path: Path.E404,
name: '404',
component: E404,
meta: { isBase: true, title: '404' }
},
{
path: '/',
redirect: Path.LOGIN // 默认加载的路由
},
{ path: '*', redirect: Path.E404 }
]
const createRouter = () => {
return new VueRouter({
mode: 'hash',
routes: constantRoutes,
scrollBehavior(to, from, savedPosition = { x: 0, y: 0 }) {
return savedPosition
}
})
}
// 处理重复点击同一个路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
//判断路由是否存在
VueRouter.prototype.hasRoute = function (path) {
return this.getRoutes().some(route => route.path === path)
}
VueRouter.prototype.constantRoutes = constantRoutes
/**
* 重置注册的路由导航map
*/
VueRouter.prototype.reset = function () {
const newRouter = createRouter()
this.matcher = newRouter.matcher
}
const router = createRouter()
router.beforeEach(async (to, from, next) => {
const session = store.getters.auth.session
if (from.path !== '/' && session === null) {
next(Path.LOGIN)
return
}
store.dispatch('app/setCurrentPage', to.meta)
if (from.name === null && to.path === Path.E404 && to.redirectedFrom && session === null) {
// 页面刷新 动态路由会失效 初始化路由与左侧菜单栏
await store.dispatch('init/init')
if (router.hasRoute(to.redirectedFrom)) {
next(to.redirectedFrom)
} else {
next(Path.LOGIN)
}
} else {
if (session) {
next()
} else {
if (to.path === Path.LOGIN) {
next()
} else {
next(Path.LOGIN)
}
}
}
})
export default router