美文网首页
全局路由守卫进行跳转拦截

全局路由守卫进行跳转拦截

作者: 冰点雨 | 来源:发表于2022-06-24 15:52 被阅读0次

    在router文件夹下index.js下进行拦截

    //全局守卫:前置守卫(在路由跳转之前进行判断)
    router.beforeEach(async (to, from, next) => {
      //to:获取到要跳转到的路由信息
      //from:获取到从哪个路由跳转过来来的信息
      //next: next() 放行  next(path) 放行
      let token = store.state.use.token;
      let name = store.state.use.userInfo.name;
      //  登录
      if (token) {
        //已经登录而且还想去登录------不行
        if(to.path=="/login"||to.path=='/register'){
          next('/');
        }else{
          //已经登陆了,访问的是非登录与注册
          //登录了且拥有用户信息放行
          if (name) {
              next();
           } else {
            //登陆了且没有用户信息
             //在路由跳转之前获取用户信息且放行
             try {
              await store.dispatch("getUserInfo");
              next();
             } catch (error) {
              //token失效从新登录
              await store.dispatch('userLogout');
              next('/login')
             }
           }
        }
      }else{
        //未登录:不能去交易相关、不能去支付相关【pay|paysuccess】、不能去个人中心
          //未登录去上面这些路由-----登录
          let toPath = to.path;
          if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
            //把未登录的时候向去而没有去成的信息,存储于地址栏中【路由】
            next('/login?redirect='+toPath);
          }else{
             //去的不是上面这些路由(home|search|shopCart)---放行
             next();
          }
      }
    });
    

    特别注意:未登录状态,跳转需要登录的页面时,把未登录的时候向去而没有去成的信息,存储于地址栏中【路由】。登录成功再把相关参数传过去

    把信息存储在地址栏中

     let toPath = to.path;
          if(toPath.indexOf('/pay')!=-1){
            //把未登录的时候向去而没有去成的信息,存储于地址栏中【路由】
            next('/login?redirect='+toPath);
          }
    

    登录后跳转指定路由,并传递参数

     //登录的路由组件:看路由当中是否包含query参数,有:调到query参数指定路由,没有:调到home
                    let toPath = this.$route.query.redirect || "/home";
                    this.$router.push(toPath);
    

    相关文章

      网友评论

          本文标题:全局路由守卫进行跳转拦截

          本文链接:https://www.haomeiwen.com/subject/lctbvrtx.html