在我的应用程序中,一些路由只对经过身份验证的用户可访
当未经身份验证的用户点击必须登录的链接时,他将被重定向到登录组件 .
如果用户成功登录, I would like to redirect him to the URL he requested before he had to log in . 但是, there also should be a default route ,以防用户在登录前未请求其他URL .
How can I achieve this using vue-router?
My code without redirect after login
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()
}
}
)
My login function in my login component
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('/')
})
我会非常感谢任何帮助!
4 回答
以一种不同的方式,这可以通过在您想要重定向时在路由中添加查询参数来实现,然后在设置参数时检查您何时登录;如果已设置,则使用它或以其他方式回退root .
在代码中应该看起来像这样:
Put an action to your link for example:
The login submit action
希望能帮助到你 .
我知道这是旧的,但它是谷歌的第一个结果,对于那些只想要它给你的人,这是你添加到你的两个文件 . 在我的情况下,我使用firebase进行身份验证 .
路由器
这里的关键是
const loginpath = window.location.pathname;
,我得到他们第一次访问的相对路径,然后下一行next({ name: 'Login', query: { from: loginpath } });
我在重定向中作为查询传递 .登录页面
这里没有魔法你只会注意到我对用户进行身份验证的行为
this.$router.replace(this.$route.query.from);
它会将它们发送到我们之前生成的查询网址 .我将更详细地充实这个逻辑,但它按原样工作 . 我希望这可以帮助那些遇到此页面的人 .
Much easier with this library和登录功能是
这将有助于你@Schwesi .