我有以下代码:
router.beforeEach((to, from, next) => {
if (to.name !== from.name) {
store
.dispatch("fetchCurrentUser")
.then(() => {
console.log('then');
// do something
next();
})
.catch(() => {
console.log('catch');
router.push("/login");
next();
});
} else {
next();
}
// next();
});
我正在尝试获取当前用户,如果成功,则对该数据执行某些操作,如果请求不成功,则将用户重定向到登录页面。但是 next () 调用不起作用,我在控制台中得到了“then”或“catch”,但是重定向没有发生并且无限循环开始了。但是,如果我从条件(注释行)中获取 next (),则重定向工作正常。
最佳答案
要重定向,您应该使用 next('/')
或 next({ path: '/' })
。
来自文档:
next: Function: this function must be called to resolve the hook. The action depends on the arguments provided to next:
next(): move on to the next hook in the pipeline. If no hooks are left, the navigation is confirmed.
next(false): abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.
next('/') or next({ path: '/' }): redirect to a different location. The current navigation will be aborted and a new one will be started. You can pass any location object to next, which allows you to specify options like replace: true, name: 'home' and any option used in router-link's to prop or router.push
关于vue.js - vue router next() 函数在 router.beforeEach 中的 Promise 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55379683/