vue2.0 实现导航守卫的具体用法(路由守卫)
路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。
对此,vue-route提供的beforeRouteUpdate可以方便地实现导航守卫(navigation-guards)。
导航守卫(navigation-guards)这个名字,听起来怪怪的,但既然官方文档是这样翻译的,就姑且这么叫吧。
贴上文档地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
全局守卫
你可以使用router.beforeEach注册一个全局前置守卫:
constrouter=newVueRouter({...})
router.beforeEach((to,from,next)=>{
//...
})
当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫resolve完之前一直处于等待中。
每个守卫方法接收三个参数:
- to:Route:即将要进入的目标路由对象
- from:Route:当前导航正要离开的路由
- next:Function:一定要调用该方法来resolve这个钩子。执行效果依赖next方法的调用参数。
- next():进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是confirmed(确认的)。
- next(false):中断当前的导航。如果浏览器的URL改变了(可能是用户手动或者浏览器后退按钮),那么URL地址会重置到from路由对应的地址。
- next('/')或者next({path:'/'}):跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
- next(error):(2.4.0+)如果传入next的参数是一个Error实例,则导航会被终止且该错误会被传递给router.onError()注册过的回调。
确保要调用next方法,否则钩子就不会被resolved。
下面写一个例子:
1.列举需要判断登录状态的“路由集合”,当跳转至集合中的路由时,如果“未登录状态”,则跳转到登录页面LoginPage;
2.当直接进入登录页面LoginPage时,如果“已登录状态”,则跳转到首页HomePage;
importVuefrom'vue';
importRouterfrom'vue-router';
importLoginPagefrom'@/pages/login';
importHomePagefrom'@/pages/home';
importGoodsListPagefrom'@/pages/good-list';
importGoodsDetailPagefrom'@/pages/good-detail';
importCartPagefrom'@/pages/cart';
importProfilePagefrom'@/pages/profile';
Vue.use(Router)
constrouter=newRouter({
routes:[
{
path:'/',//默认进入路由
redirect:'/home'//重定向
},
{
path:'/login',
name:'login',
component:LoginPage
},
{
path:'/home',
name:'home',
component:HomePage
},
{
path:'/good-list',
name:'good-list',
component:GoodsListPage
},
{
path:'/good-detail',
name:'good-detail',
component:GoodsDetailPage
},
{
path:'/cart',
name:'cart',
component:CartPage
},
{
path:'/profile',
name:'profile',
component:ProfilePage
},
{
path:'**',//错误路由
redirect:'/home'//重定向
},
]
});
//全局路由守卫
router.beforeEach((to,from,next)=>{
console.log('navigation-guards');
//to:Route:即将要进入的目标路由对象
//from:Route:当前导航正要离开的路由
//next:Function:一定要调用该方法来resolve这个钩子。执行效果依赖next方法的调用参数。
constnextRoute=['home','good-list','good-detail','cart','profile'];
letisLogin=global.isLogin;//是否登录
//未登录状态;当路由到nextRoute指定页时,跳转至login
if(nextRoute.indexOf(to.name)>=0){
if(!isLogin){
console.log('whatfuck');
router.push({name:'login'})
}
}
//已登录状态;当路由到login时,跳转至home
if(to.name==='login'){
if(isLogin){
router.push({name:'home'});
}
}
next();
});
exportdefaultrouter;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。