• 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 放在最后,这样就可以实现前置守卫

    希望自己写的东西能够对大家有所帮助!谢谢
  • 相关阅读:
    LintCode 27. 拓扑排序 DFS实现
    LintCode 155. 二叉树的最小深度
    LintCode 90. k数和 II
    LintCode 33. N皇后问题
    Oracle分组后取某列最大值的行数据
    Oracle日期范围
    Mongo可视化工具基本操作
    修改winform安装包写日志文件权限
    Winform安装包出现无法访问网络位置
    ComboBox的真实值和显示值
  • 原文地址:https://www.cnblogs.com/mrxinxin/p/10170694.html
Copyright © 2020-2023  润新知