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

重定向 Vue.js

Stafan卡卡西

2020-03-12

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

如果用户成功登录,我想将他重定向到他必须登录之前请求的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('/')
          })



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

第970篇《使用vue-router登录后重定向到请求的页面》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
乐猪猪 2020.03.12

使用此库 和登录功能要容易得多

let redirect = this.$auth.redirect();
this.$auth
  .login({
    data: this.model,
    rememberMe: true,
    redirect: { name: redirect ? redirect.from.name : "homepage",  query: redirect.from.query },
    fetchUser: true
  })

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android