在我的应用程序中,某些路由仅对经过身份验证的用户可用。
当未经身份验证的用户单击必须登录的链接时,他将被重定向到登录组件。
如果用户成功登录,我想将他重定向到他必须登录之前请求的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('/')
})
我将非常感谢你提供的任何帮助!
这可以通过在路由中添加重定向路径作为查询参数来实现。
然后,当你登录,你必须检查重定向参数设置:
-如果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*/ })
}
希望能帮助到你。
@V当您进行第三方登录时,例如,对于google帐户auth,用户将被重定向到另一个链接,即第三方供应商链接以登录然后再返回到我们的应用程序,您该怎么做?