vue.js - vue router next() 函数在 router.beforeEach 中的 Promise 中不起作用

标签 vue.js vue-router

我有以下代码:

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/

相关文章:

html - 无法使用 VueJS 渲染图像

javascript - 如何使用 vue.js 绑定(bind)动态添加的表单输入

vue.js - 在自定义指令中模拟 v-if 指令

vue.js - Vue js单页和带有标题问题的侧边栏

vue.js - Vuetify v-flex 中的 child-flex 选项有什么用?

javascript - 如何将商店中对象的动态属性用作 v 模型?

javascript - Vue.js 可排序列表 - 通过 AJAX 更新模型并保存更改位置

vue-router - 路由器链接与vue和vuetify混淆

vue.js - vue-router:如何检查当前路线是路线还是其子路线之一?

vue.js - VueJS通过路由器的next()参数传递