把用户原操作页面的地址作为重定向路由的参数

main.js或者router.js文件
//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (!token && to.path !== '/login') {
    next({
      path: '/login',
      query: { redirect: to.fullPath } // 将要跳转路由的path作为参数,传递到登录页面
    })
  } else {
    next()
  }
http.js 请求拦截
// http响应拦截器
axios.interceptors.response.use(
  data => {
    tryHideFullScreenLoading()
    return data
  },
  error => {
    //当返回信息为未登录或者登录失效的时候重定向为登录页面
    if (error.response.status == '401') {
      Message.error({
        message: '登录已过期,请您重新登录!'
      })
      localStorage.clear()
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.fullPath } //从哪个页面跳转
      })
    }
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)
login.vue
 submitForm (formName) {
    this.$refs[formName].validate(async (valid) => {
       if (valid) {
         let res = await this.$axios.post(this.API.login.login, {
           username: this.form.username,
           password: this.form.password
         })
         let { Status, Result, Msg } = res.data
         if (Status == "true") {
           this.$message.success('恭喜您登录成功')
           localStorage.setItem("username", Result.username)
           localStorage.setItem("brand", Result.brand)
           localStorage.setItem("token", Result.token)
           if (this.$route.query.redirect) { //如果存在参数
             let redirect = this.$route.query.redirect
             this.$router.push(redirect)//则跳转至进入登录页前的路由
           } else {
             this.$router.push('/')//否则跳转至首页
           }
         } else {
           this.$message.error(Msg)
         }
       }
     })
   },
Logo

前往低代码交流专区

更多推荐