首页 > 其他 > 详细

路由导航守卫

时间:2020-10-09 11:47:59      阅读:33      评论:0      收藏:0      [点我收藏+]

需求:当我进入某一页面前需要判断当前页面是否登录,是否具有权限。如果没有登录则进入登录页面进行登录,没有权限进入a页面,有权限进入b页面。

思路:通过动态路由路由守卫的beforeEach来实现。

在router.js中添加代码

1 router.beforeEach((to, from, next) => {
2   console.log(to, ‘即将要进入的目标 路由对象‘)
3   console.log(from, ‘当前导航正要离开的路由‘)
4   console.log(next, ‘Function‘)
5   // to: Route: 即将要进入的目标 路由对象
6   // from: Route: 当前导航正要离开的路由
7   // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
8  //具体实现方式待补充。。
9 next() 10 })

vue中提供了三种钩子

1.全局导航守卫钩子函数

2.路由独享钩子函数

3.组件内钩子函数

一、全局导航守卫钩子函数

1.beforeEach:在跳转路由前执行的函数

一定要调用next方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数,如果不添加next函数,终止导航

2.afterEach:在跳转路由后执行的函数

  此时已经跳转路由完成,无需调用next参数

二、路由独享钩子函数

1.beforeEnter

 1 {
 2     path: ‘/‘,
 3     name: ‘carrie‘,
 4     component: resolve => require([‘./../view/carrie.vue‘], resolve),
 5     beforeEnter: (to, from, next)=> {
 6     console.log(to, ‘beforeEnter即将要进入的目标 路由对象‘)
 7     console.log(from, ‘beforeEnter当前导航正要离开的路由‘)
 8     console.log(next, ‘beforeEnter Function‘)
 9       next()
10  }

三、组件内钩子函数

1.beforeEnter

2.beforeUpdate

3.beforeLeave

 1   created() {},
 2   beforeRouteEnter(to, from, next) {
 3     console.log(to, ‘beforeRouteEnter to‘)
 4     console.log(from, ‘beforeRouteEnter from‘)
 5     console.log(next, ‘beforeRouteEnter next‘)
 6     next()
 7   },
 8   beforeRouteUpdate(to, from, next) {
 9     console.log(to, ‘beforeRouteUpdate to‘)
10     console.log(from, ‘beforeRouteUpdate from‘)
11     console.log(next, ‘beforeRouteUpdate next‘)
12     next()
13   },  
14   beforeRouteLeave(to, from, next) {
15     console.log(to, ‘beforeRouteLeave to‘)
16     console.log(from, ‘beforeRouteLeave from‘)
17     console.log(next, ‘beforeRouteLeave next‘)
18     next()
19   },
20   methods:{}
beforeRouteEnter访问不了this,beforeRouteUpdate和beforeRouteLeave可以访问this

next()//跳转to.name路径
next(false) //终止导航
next(/XX) //跳转指定路径

路由导航守卫

原文:https://www.cnblogs.com/lss0322/p/13784471.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!