Warm tip: This article is reproduced from serverfault.com, please click

vue.js-使用vue-router登录后重定向到请求的页面

(vue.js - Redirect to requested page after login using vue-router)

发布于 2017-08-24 08:44:15

在我的应用程序中,某些路由仅对经过身份验证的用户可用。
当未经身份验证的用户单击必须登录的链接时,他将被重定向到登录组件。

如果用户成功登录,我想将他重定向到他必须登录之前请求的URL但是,还应该有一个默认路由,以防用户在登录之前未请求其他URL。

如何使用vue-router实现此功能?


登录后我的代码没有重定向
router.beforeEach(
    (to, from, next) => {
        if(to.matched.some(record => record.meta.forVisitors)) {
            next()
        } else if(to.matched.some(record => record.meta.forAuth)) {
            if(!Vue.auth.isAuthenticated()) {
                next({
                    path: '/login'
                    // Redirect to original path if specified
                })
            } else {
                next()
            }
        } else {
            next()
        }
    }        
)



我的登录功能在我的登录组件中

login() {
    var data = {
        client_id: 2,
        client_secret: '**************',
        grant_type: 'password',
        username: this.email,
        password: this.password
    }
    // send data
    this.$http.post('oauth/token', data)
         .then(response => {
             // authenticate the user
             this.$auth.setToken(response.body.access_token,
             response.body.expires_in + Date.now())
             // redirect to route after successful login
             this.$router.push('/')
          })



我将非常感谢你提供的任何帮助!

Questioner
Schwesi
Viewed
11
V. Sambor 2020-03-14 18:22:26

这可以通过在路由中添加重定向路径作为查询参数来实现

然后,当你登录,你必须检查重定向参数设置:
-如果IS集重定向到路径在参数中发现
-如果设置,你可以在根回退。


对链接进行操作,例如:

onLinkClicked() {
  if(!isAuthenticated) {
    // If not authenticated, add a path where to redirect after login.
    this.$router.push({ name: 'login', query: { redirect: '/path' } });
  }
}

登录提交动作

submitForm() {
  AuthService.login(this.credentials)
    .then(() => this.$router.push(this.$route.query.redirect || '/'))
    .catch(error => { /*handle errors*/ })
}

希望能帮助到你。