报错:Avoided redundant navigation to current location: “/login“.完美解决

需求:

登陆之后才能查看主页面,否则跳转至登录页

遇到的问题:

一开始是打算直接在拦截器跳转路由的,发现会报错Avoided redundant navigation to current location: "/login".

后来灵机一动,用了全局路由守卫,完美解决

request.interceptors.request.use(config=>{
    config.headers['Content-Type']='application/json;charset=utf-8'
    let user=localStorage.getItem("user")
    if(!user){
        router.push("/login")
    }
    return config
},error=> {
    return Promise.reject(error)
})

报错:

解决方案:

添加全局路由守卫,并通过localStorage存储信息

全局路由守卫:

router.beforeEach((to,from,next)=>{
    let user = localStorage.getItem("user");
    if(!user){
        if(to.path!=='/login'){
            next({path:"/login"})
        }else{
            next()
        }
    }else{
        next()
    }
})

登录界面的逻辑判断:

         request.post("/user/login",this.form).then(
              res=>{
                if(res.code==='0'){
                  this.$message({
                    type:"success",
                    message:"登录成功"
                  })
                  localStorage.setItem("user",JSON.stringify(res.data))
                  this.$router.push("/")
                }else{
                  this.$message({
                    type:"error",
                    message:res.msg
                  })
                }
              }
          )

你可能感兴趣的:(前端,vue.js,前端,javascript)