vue-router 的 beforeEach 偶尔会表现出奇怪的行为

Bil*_*onk 2 javascript vue.js vue-router

我有以下代码:

const routes = [
    { path: '/', component: FooView },
    { path: '/bar', component: BarView } 
];

const router = new VueRouter({
    routes
});

router.beforeEach(function(to, from, next) {
    if (to.path === '/bar') {
        next('/');    
    }

    next();
});
Run Code Online (Sandbox Code Playgroud)

如果我省略了太多,而您需要查看与路由器相关的其他代码段,请告诉我,以便我填写。

如果我打开一个新选项卡并导航到“/#/bar”,我将成功重定向到“/#”。但是,如果我随后进入地址栏并手动添加“/#/bar”并按回车键,则不会被重定向。如果我再次在地址栏中按 Enter 键,我将重定向。

我已经逐步完成了控制台中的代码,我看到它正在调用next('/'),我看到它push('/')在内部调用的位置,next('/')但直到我第二次在地址栏中按 Enter 键才会生效。

我试过使用,router.replace('/')但行为是一样的。我试过beforeEnter在单独的路线上使用,但行为也是一样的。

我发现讨论类似行为的两个链接是:https : //github.com/vuejs/vue-router/issues/748https://forum.vuejs.org/t/router-beforeeach-if-manually -input-adress-in-browser-it-does-not-work/12461/2但都没有帮助我。

有人能解释一下吗?我正在尝试做的事情与 vue-router 提供的功能之间是否存在脱节?如果这种行为不是预期的,有人可以提出解决方法吗?

小智 5

vue-router官方文档中,不推荐你实现beforeEach()的方式。以下是文档中的内容:

确保在通过导航守卫的任何给定传递中,下一个函数只被调用一次。它可以出现多次,但前提是逻辑路径没有重叠,否则钩子永远不会被解析或产生错误。这是一个重定向用户到 /login 的示例,如果他们未通过身份验证:

// BAD
router.beforeEach((to, from, next) => {
  if (!isAuthenticated) next('/login')
  // if the user is not authenticated, `next` is called twice
  next()
})
// GOOD
router.beforeEach((to, from, next) => {
  if (!isAuthenticated) next('/login')
  else next()
})
Run Code Online (Sandbox Code Playgroud)

不知道为什么第一个是一个不好的例子,因为两个示例代码在逻辑上应该完全相同。我的代码在第一次使用 next('/') 重定向路径时弹出错误,但是,重新路由仍然成功。寻找专业人士的答案。