如何在 beforeRouterEnter 守卫中调用 next()
How to call next() in the beforeRouterEnter guard
我已经在这个问题上停留了几个小时了。
我正在使用 Vue3
我正在尝试使用 beforeRouterEnter
守卫来检查当前登录的用户角色,并基于此将用户重定向到适当的路由。
提交登录表单(从登录页面)后,userRoleId
存储在 vuex 中,我被重定向到主页。主页有以下脚本:
beforeRouteEnter(to, from, next) {
next((vm) => {
if (vm.$store.getters.userRoleId == USER) {
next("/us");
return;
}
if (vm.$store.getters.userRoleId == ADMIN) {
next("/ad");
return;
}
if (vm.$store.getters.userRoleId == SUPER_ADMIN) {;
next("/sa");
return;
}
next();
});
},
我不断收到以下警告'The "next" callback was called more than once in one navigation guard when going from "/" to "/". It should be called exactly one time in each navigation guard. This will fail in production.'
错误出现在以下情况:我未登录并移动到 else 块(一旦到达 next()
行),或者当我登录并从内部登录时 [=一旦达到 next()
,14=] 语句为真 - 导致重定向不起作用。
在 next
回调中调用 next
是错误的。那个时候导航已经完成了,这应该是用router.push
重定向,这种逻辑属于组件mounted
(next
回调在它之后运行)而不是路由器卫士。
这里不应该有重定向,因为它们是不必要的。商店是 全局的 并且可以直接导入而不是在 vm
.
上访问
应该是:
import store from '...';
...
beforeRouteEnter(to, from, next) {
if (store.getters.userRoleId == USER) {
next("/us");
} else if ... {
...
} else {
next();
}
},
我已经在这个问题上停留了几个小时了。 我正在使用 Vue3
我正在尝试使用 beforeRouterEnter
守卫来检查当前登录的用户角色,并基于此将用户重定向到适当的路由。
提交登录表单(从登录页面)后,userRoleId
存储在 vuex 中,我被重定向到主页。主页有以下脚本:
beforeRouteEnter(to, from, next) {
next((vm) => {
if (vm.$store.getters.userRoleId == USER) {
next("/us");
return;
}
if (vm.$store.getters.userRoleId == ADMIN) {
next("/ad");
return;
}
if (vm.$store.getters.userRoleId == SUPER_ADMIN) {;
next("/sa");
return;
}
next();
});
},
我不断收到以下警告'The "next" callback was called more than once in one navigation guard when going from "/" to "/". It should be called exactly one time in each navigation guard. This will fail in production.'
错误出现在以下情况:我未登录并移动到 else 块(一旦到达 next()
行),或者当我登录并从内部登录时 [=一旦达到 next()
,14=] 语句为真 - 导致重定向不起作用。
在 next
回调中调用 next
是错误的。那个时候导航已经完成了,这应该是用router.push
重定向,这种逻辑属于组件mounted
(next
回调在它之后运行)而不是路由器卫士。
这里不应该有重定向,因为它们是不必要的。商店是 全局的 并且可以直接导入而不是在 vm
.
应该是:
import store from '...';
...
beforeRouteEnter(to, from, next) {
if (store.getters.userRoleId == USER) {
next("/us");
} else if ... {
...
} else {
next();
}
},