import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "login" */ '../components/LoginPage.vue')
},
// 重定向,
{
path: '/',
redirect:'/login'
},
{
path: '/home',
name: 'home',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "home" */ '../components/HomePage.vue')
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// 挂载路由导航守卫
router.beforeEach((to,from,next) =>{
// to将要访问的路径
// from 代表从哪个路径来的
// next 是一个函数表示放行
// next() 放行 next("/login") 强制跳转到login页面
if(to.path === '/login'){
// 直接放行
return next();
}
// 获取token
const token = sessionStorage.getItem('token');
// 如果token不存在,表示没有登录,强制跳转到login页面
if(!token) {
return next('/login');
}
// 有token直接放行
next();
})
export default router
全局守卫(前置/后置):beforeEach、beforeResolve、afterEach
路由独享的守卫:beforeEnter
组件内的守卫:beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave