我有一个钩子可以检查用户角色是否与路由的必需元“角色”匹配。
我第一次使用用户角色输入我的路线时,它会按预期运行(将我发送到路线“ /”),但是,第二次,如果我在浏览器地址栏中输入了相同的路线或单击将我发送到同一路由的按钮,将记录console.log('角色不匹配'),但next()函数似乎不起作用,因为我没有重定向到路径:'/',并且路由组件正常加载。
if (to.matched.some(record => record.meta.role)) {
if (to.meta.role === response.data.tokenOwner.role) {
// User are allowed to enter in this route
next()
} else {
// Here is my problem
console.log('Role does not match')
next({
path: '/',
query: { redirect: to.fullPath }
})
}
} else {
next()
}
Bellow跟随我的整个beforeEach。
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
try {
AuthenticationService.validateToken({
token: store.state.token
}).then((response) => {
if (response.status === 200) {
if (to.matched.some(record => record.meta.role)) {
if (to.meta.role === response.data.tokenOwner.role) {
// User are allowed to enter in this route
next()
} else {
// Here is my problem
console.log('Role does not match')
next({
path: '/',
query: { redirect: to.fullPath }
})
}
} else {
next()
}
} else {
store.dispatch('setToken', null)
store.dispatch('setUser', null)
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
next()
}).catch(() => {
store.dispatch('setToken', null)
store.dispatch('setUser', null)
next({
path: '/login',
query: { redirect: to.fullPath }
})
})
} catch (error) {
console.log(error)
this.error = error.response.data.error
}
} else {
next()
}
})