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
|