index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // 引入第三方库
  2. import Vue from 'vue'
  3. // vue-router 路由
  4. // npm install vue-router@3
  5. // @3 =>vue2
  6. // @4 => vue3
  7. import VueRouter from 'vue-router'
  8. import home from '../views/home.vue'
  9. // 引入页面
  10. import Vase from '../views/List.vue'
  11. import Collect from '../components/collect.vue'
  12. import Add from '../components/add.vue'
  13. // 实例化
  14. Vue.use(VueRouter)
  15. // 路由守卫
  16. // 1.全局路由守卫
  17. // beforeEach 前置路由守卫
  18. // afterEach 后置路由守卫
  19. // 2.独享路由守卫:守卫哪写在哪
  20. // beforeEnter
  21. // 3.组建内的路由守卫 =>components/vase1.vue
  22. // 进入守卫 beforeRouteEnter
  23. // 离开守卫 beforeRouteLeave
  24. const routes = [
  25. {
  26. path:'/',
  27. name: 'home',
  28. component: home
  29. },
  30. {
  31. path:'/home',
  32. name: 'home',
  33. component: home,
  34. // 路由重定向 redirect
  35. redirect:'/',
  36. children:[
  37. {
  38. path:'vase1',
  39. component:()=>import("../components/vase1.vue")
  40. },
  41. {
  42. path:'vase2',
  43. component:()=>import("../components/vase2.vue"),
  44. meta:{title:"第二页"},
  45. // beforeEnter: (to, from, next) => {
  46. // // ...
  47. // console.log("开始独享")
  48. // if(localStorage.getItem("bb")==="222") {
  49. // next();
  50. // } else {
  51. // alert("人员信息不存在")
  52. // }
  53. // }
  54. },
  55. ]
  56. },
  57. // 1.先配置路由的路径:path 2.起名字 3.存放路径页面
  58. {
  59. path:"/list",
  60. // name: 'list',
  61. component: Vase,
  62. meta:{isAuth:true,title:'列表页'},
  63. // 二级路由/多级路由
  64. children:[
  65. {
  66. // params传参:路径/:xxx/:xxx/:xxx
  67. path:'collect/:name/:age',
  68. name:"ANew",
  69. component: Collect
  70. },
  71. {
  72. path:'add',
  73. component: Add
  74. }
  75. ]
  76. },
  77. {
  78. path: '/new',
  79. // 路由的懒加载
  80. component:()=>import("../views/New.vue"),
  81. meta:{title:"新页面"}
  82. }
  83. // {
  84. // path:'/new',
  85. // component:() => import(/* webpackChunkName: "new" */"../views/New.vue")
  86. // }
  87. ]
  88. const router = new VueRouter({
  89. mode: 'history',
  90. base: process.env.BASE_URL,
  91. routes
  92. })
  93. export default router
  94. // 全局中前置路由守卫
  95. router.beforeEach((to,from,next)=>{
  96. // 1.to => 进入的目标对象
  97. // 2.from => 离开的目标对象
  98. // 3.next => 下一步所执行的内容
  99. if(to.meta.isAuth) {
  100. console.log("进入1")
  101. if(localStorage.getItem("aa")==="111") {
  102. next()
  103. } else {
  104. alert("当前用户未登录")
  105. }
  106. } else {
  107. next()
  108. }
  109. })
  110. // 全局中后置路由守卫
  111. router.afterEach((to,from,next)=>{
  112. console.log("进入2");
  113. document.title = to.meta.title || '路由守卫'
  114. })