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

新手上路,请多包涵

在我的应用程序中,某些路由仅供经过身份验证的用户访问。

当未经身份验证的用户单击必须登录的链接时,他将被重定向到登录组件。

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

原文由 Schwesi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 911
2 个回答

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

然后当你登录时,你必须检查是否设置了重定向参数:

  • 如果 IS 设置重定向到参数中找到的路径

  • 如果 设置,则可以回退到 root。


对您的链接进行操作,例如:

 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*/ })
}

原文由 V. Sambor 发布,翻译遵循 CC BY-SA 4.0 许可协议

我知道这是旧的,但它是谷歌的第一个结果,对于那些只想把它给你的人来说,这是你添加到你的两个文件中的内容。在我的情况下,我使用 firebase 进行身份验证。

路由器

这里的关键行是 const loginpath = window.location.pathname; 我得到他们第一次访问的相对路径,然后下一行 next({ name: 'Login', query: { from: loginpath } }); 我在重定向中作为查询传递。

 router.beforeEach((to, from, next) => {
    const currentUser = firebase.auth().currentUser;
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

    if (requiresAuth && !currentUser) {
        const loginpath = window.location.pathname;
        next({ name: 'Login', query: { from: loginpath } });
    } else if (!requiresAuth && currentUser) next('menu');
    else next();
});

登录页面

这里没有魔法,您只会注意到我对用户进行身份验证时的操作 this.$router.replace(this.$route.query.from); 它将它们发送到我们之前生成的查询 url。

 signIn() {
    firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
        (user) => {
            this.$router.replace(this.$route.query.from);
        },
        (err) => {
            this.loginerr = err.message;
        },
    );
},

我将更详细地充实这个逻辑,但它按原样工作。我希望这对那些遇到此页面的人有所帮助。

原文由 Phillip 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题