在我的应用程序中,某些路由仅供经过身份验证的用户访问。
当未经身份验证的用户单击必须登录的链接时,他将被重定向到登录组件。
如果用户成功登录, 我想将他重定向到他必须登录之前请求的 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 许可协议
这可以通过在路由中添加 重定向路径 作为 查询参数 来实现。
然后当你登录时,你必须检查是否设置了重定向参数:
如果 IS 设置重定向到参数中找到的路径
如果 未 设置,则可以回退到 root。
对您的链接进行操作,例如:
登录提交动作: