vue-router登录校验后跳转到之前指定页面如何实现

  两个需求:1、用户点击购买需要下单,并跳转到订单页面,但是如果用户没有登录的话,中间有登录验证,会拦截;2、点击购买的时候,登录校验成功了,跳转到订单页面时,订单已创建,去付款即可。

一、解决方案对1:

  大概思路:1、当你想进入 http://localhost:8080/order(该页面需要登录授权),2、检查是否登录,如果没有登录就跳转到登录页,需要将上一页的path(‘/order’)作为query存到login页地址中,如:http://localhost:8080/login?redirect=%2Forder

router.beforeEach((to, from ,next) => {
    const token = store.getters.userInfo
    if(to.matched.some(record => record.meta.requireAuth || record.meta.homePages)){
        //路由元信息requireAuth:true,或者homePages:true,则不做登录校验
        next()
    }else{
        if(token){//判断用户是否登录
            if(Object.keys(from.query).length === 0){//判断路由来源是否有query,处理不是目的跳转的情况
                next()
            }else{
                let redirect = from.query.redirect//如果来源路由有query
                if(to.path === redirect){//这行是解决next无限循环的问题
                    next()
                }else{
                    next({path:redirect})//跳转到目的路由
                }
            }
        }else{
            if(to.path==="/login"){
                next()
            }else{
                next({
                      path:"/login",
                      query: {redirect: to.fullPath}//将目的路由地址存入login的query中
                })
            }
        }
    }
    return
})

二、解决方案对2:

  order有2种情况进入,一种直接点击,一种就是上面的跳转,跳转需要传入选取订单的id,用来创建订单。

  大致思路:1、建立2种路由跳转指向同一个组件;2、通过不同路由路径,在组件内生命周期,执行不同的操作

    {
        path:'/order',
        name:'order',
        component:() => import('@/views/system/order')
    },
    {
        path:'/order/:id',
        name:'order',
        component:() => import('@/views/system/order')
    }
    mounted(){
        let _id = this.$route.params.id//看是那种跳转路径
        if(!_id){
            this.fetchData()
        }else{
            orderFromHomeApi(_id).then(res => {
                if(res.status === 200){
                    this.fetchData()
                }
            })
        }
    }

猜你喜欢

转载自www.cnblogs.com/goloving/p/9147975.html