【问题标题】:How to redirect to desired page in Vue js using vue-router?如何使用 vue-router 在 Vue js 中重定向到所需的页面?
【发布时间】:2020-07-17 15:05:40
【问题描述】:

这是requiresAuthrequiresGuest 的代码

requiresAuth:满足此条件的用户无法进入登录页面或注册页面(/ 的元数据)

requiresGuest :满足此条件的用户不能转到/ 或具有requiresAuth/login/signup 的任何其他页面

这两个条件对我的页面非常有效

问题

Step-1 可以说我得到了一个类似localhost:8000/api/createapi/.......的网址

Step-2所以目前我没有登录,我输入上面的URL,它会将我重定向到log in页面(这是预期的)

Step-3 但是当我重新登录时,它会将我重定向到/(这不理想

我想要什么

Step-2 之后,当我登录时,它会自动将我重定向到localhost:8000/api/createapi/....... 因为那是Step-1中请求的URL

router.beforeEach((to, from, next) => {    
// check for required auth guard
  if (to.matched.some(record => record.meta.requiresAuth)) {
    requiresAuthLogic(to, next, from)
  } else if (to.matched.some(record => record.meta.requiresGuest)) {
    requiresGuestLogic(to, next)
  } else {
    // Proceed to route
    next()
  }
})
function requiresAuthLogic (to:Route, next:Function) {
  // check if NOT logged in
  if (!isUserLoggedIn()) {
    // Go to login
    next({
      path: '/login',
      query: {
        redirect: to.fullPath
     }
    })
  } else if (isUserEmailVerified() === true) {
    // Proceed to route
    next()
  }
}

function requiresGuestLogic (to:Route, next:Function) {
  if (isUserLoggedIn() && isUserEmailVerified() === true) {
    next({
      path: '/',
      query: {
        redirect: to.fullPath
      }
    })
  } else {
    // Proceed to route
    next()
  }
}

【问题讨论】:

    标签: javascript node.js vue.js vue-router


    【解决方案1】:

    如果我理解正确,您需要使用通过重定向参数传递的值

    如果登录成功,这应该在你的登录功能中完成,你还没有分享你的登录功能,但是这样的:

    loginUser() {
        this.$store.dispatch('loginUser', {
            email: this.email,
            password: this.password
        })
            .then(() => {
                this.$router.push(this.$route.query.redirect)
            })
        }
    

    【讨论】:

    • 是的,你正确地理解了我,这样做就像一个魅力......你节省了我很多时间......我认为我的router.ts有问题因此没有发布登录方法:P
    • 太好了,很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2020-01-11
    • 2017-03-04
    • 2018-02-02
    • 2019-04-21
    • 1970-01-01
    • 2015-11-17
    • 2020-06-03
    • 2020-10-08
    相关资源
    最近更新 更多