index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // 该文件专门用于创建整个应用的路由器
  2. import VueRouter from 'vue-router'
  3. //引入组件
  4. import About from '../pages/About'
  5. import Home from '../pages/Home'
  6. import News from '../pages/News'
  7. import Message from '../pages/Message'
  8. import Detail from '../pages/Detail'
  9. //创建并暴露一个路由器
  10. const router = new VueRouter({
  11. routes:[
  12. {
  13. name:'guanyu',
  14. path:'/about',
  15. component:About,
  16. meta:{title:'关于'} //路由元信息,就是程序员自定义的信息
  17. },
  18. {
  19. name:'zhuye',
  20. path:'/home',
  21. component:Home,
  22. meta:{title:'主页'},
  23. children:[
  24. {
  25. name:'xinwen',
  26. path:'news',
  27. component:News,
  28. meta:{isAuth:true,title:'新闻'} //isAuth:是否授权,如果不需要校验,可以省略不写
  29. },
  30. {
  31. name:'xiaoxi',
  32. path:'message',
  33. component:Message,
  34. meta:{isAuth:true,title:'消息'},
  35. children:[
  36. {
  37. name:'xiangqing',
  38. path:'detail',
  39. component:Detail,
  40. meta:{isAuth:true,title:'详情'},
  41. //props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
  42. // props:{a:1,b:'hello'}
  43. //props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
  44. // props:true
  45. //props的第三种写法,值为函数
  46. props($route){
  47. return {
  48. id:$route.query.id,
  49. title:$route.query.title,
  50. a:1,
  51. b:'hello'
  52. }
  53. }
  54. }
  55. ]
  56. }
  57. ]
  58. }
  59. ]
  60. })
  61. //全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
  62. // 普通函数、箭头函数均可
  63. router.beforeEach((to,from,next)=>{
  64. console.log('前置路由守卫',to,from)
  65. if(to.meta.isAuth){ //判断是否需要鉴权
  66. if(localStorage.getItem('school')==='atguigu'){
  67. next()
  68. }else{
  69. alert('学校名不对,无权限查看!')
  70. }
  71. }else{
  72. next()
  73. }
  74. })
  75. //全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
  76. router.afterEach((to,from)=>{
  77. console.log('后置路由守卫',to,from)
  78. document.title = to.meta.title || '硅谷系统'
  79. })
  80. export default router