vue中的前置守卫

前置守卫是为了验证用户信息真实性,一些内容只能在用户登陆以后才能进行查看,例如个人中心,我的购物车,等个人页面,非隐私页面

用router.beforeEach进行验证,这个方法必须写在router实例之后

三个参数 to===到哪里去

    from===从哪里来

    next===放行

router.beforeEach((to,from,next)=>{
        if(to.matched.some((route)=>route.meta.requireAuth)){
            if(localStorage.getItem('ticket')){
                next()
            }else{
                next('/login?returnURL='+to.path)
            }
            
        }else{
            next()
        }
    });

 to.matched.some((route)=>route.meta.requireAuth)是有效的检验方法,可以从父元素以及祖先元素进行验证,

在你需要守卫的组件上加入meta标签就可以啦,

meta:{
        requireAuth:true
     }

 在vue cli脚手架中需吧router中代码稍加改动就可以使用啦

const router= new Router({
  linkExactActiveClass: 'active',
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path:'/',
      component:Index,
      children:[
        {
          path:'channel/:id',
          component:Channel,
          children:[
            {
              path:'/topic/:num',
              component:Topic
            }
          ]
        }
        
      ]
    },{
      path:'/login',
      component:Login,
      children:[
        {
          path:'reg',
          component:Reg,
          meta:{
            requireAuth:true
          },
        },
        {
          path:'myself',
          component:Myself,
          meta:{
            requireAuth:true
          },
        }
      ]
    }
  ]
})
router.beforeEach((to,from,next)=>{
  if(to.matched.some(route=>route.meta.requireAuth)){
    const url=localStorage.getItem('login');
    if(url=='1'){
      next();
    }else{
      next('/login?returnURL='+to.path);
    }
    
  }else{
    next();
  }
  
});
export default router

 

 把 export 放在最后,这样就可以实现前置守卫

 

转载于:https://www.cnblogs.com/mrxinxin/p/10170694.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值