最佳答案
在我的应用程序中,一些路由只对经过身份验证的用户可访问。< br > 当未经身份验证的用户单击一个必须为其签名的链接时,他将被重定向到登录组件。< br >
如果用户成功登录,则 我想在他登录之前将他重定向到他请求的 URL。但是,如果用户在登录之前没有请求另一个 URL,则使用 也应该有一个默认的路线。< br > < br >
如何使用 vue-router 实现这一点? < br >
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('/')
})
}