zoukankan      html  css  js  c++  java
  • 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 放在最后,这样就可以实现前置守卫

    希望自己写的东西能够对大家有所帮助!谢谢
  • 相关阅读:
    安装kali中的一些常用工具和firefox的插件
    kali定制
    熟悉BASH命令
    kali中各目录的作用
    kali中netspeed的安装方法
    kali中常用的ctf工具
    【学生党必看】大学里,你的六个重要选择【转载】
    kali持久加密USB的制作
    elasticsearch _search结果解析
    Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]
  • 原文地址:https://www.cnblogs.com/mrxinxin/p/10170694.html
Copyright © 2011-2022 走看看