1. import Vue from 'vue'
  2. import VueRouter from 'vue-router'
  3. Vue.use(VueRouter)
  4. const routes = [
  5. {
  6. path: '/login',
  7. name: 'login',
  8. // route level code-splitting
  9. // this generates a separate chunk (about.[hash].js) for this route
  10. // which is lazy-loaded when the route is visited.
  11. component: () => import(/* webpackChunkName: "login" */ '../components/LoginPage.vue')
  12. },
  13. // 重定向,
  14. {
  15. path: '/',
  16. redirect:'/login'
  17. },
  18. {
  19. path: '/home',
  20. name: 'home',
  21. // route level code-splitting
  22. // this generates a separate chunk (about.[hash].js) for this route
  23. // which is lazy-loaded when the route is visited.
  24. component: () => import(/* webpackChunkName: "home" */ '../components/HomePage.vue')
  25. },
  26. ]
  27. const router = new VueRouter({
  28. mode: 'history',
  29. base: process.env.BASE_URL,
  30. routes
  31. })
  32. // 挂载路由导航守卫
  33. router.beforeEach((to,from,next) =>{
  34. // to将要访问的路径
  35. // from 代表从哪个路径来的
  36. // next 是一个函数表示放行
  37. // next() 放行 next("/login") 强制跳转到login页面
  38. if(to.path === '/login'){
  39. // 直接放行
  40. return next();
  41. }
  42. // 获取token
  43. const token = sessionStorage.getItem('token');
  44. // 如果token不存在,表示没有登录,强制跳转到login页面
  45. if(!token) {
  46. return next('/login');
  47. }
  48. // 有token直接放行
  49. next();
  50. })
  51. export default router

全局守卫(前置/后置):beforeEach、beforeResolve、afterEach

路由独享的守卫:beforeEnter

组件内的守卫:beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave