在我的应用程序中,某些路由仅对经过身份验证的用户可用。
当未经身份验证的用户单击必须登录的链接时,他将被重定向到登录组件。
如果用户成功登录,我想将他重定向到他必须登录之前请求的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('/')
})
我将非常感谢您提供的任何帮助!
使用此库 和登录功能要容易得多,