【问题标题】:Router async beforeEach triggers two routesRouter async beforeEach 触发两条路由
【发布时间】:2026-01-23 02:45:02
【问题描述】:

我正在尝试在路由保护中等待异步响应。问题是命中了两条路线。

当页面加载完毕,/路由立即触发,紧接着是我的目标路由

router.beforeEach(async (to, from, next) => {
  await new Promise(resolve => {
    setTimeout(resolve, 500)
  })
  next()
})

router.beforeEach((to, from, next) => {
    setTimeout(next, 500)
  })
})

在我的日志中,我在访问 /foo 时看到两个条目,第一个是 /,然后是 500 毫秒后的 /foo。我希望只看到后者:

setup(props, { root }) {
    const hideNav = computed(() => {
      console.log(root.$route.path)
      return root.$route.meta?.hideNav
    })

    return {
      hideNav
    }
  }
})

我正在使用vue@2.6.12vue-router@3.4.9

【问题讨论】:

  • 你能分享一下小例子或沙盒链接吗?
  • 我无法重现您的问题。 jsfiddle.net/opz6wyu4/1,我的复制代码有什么遗漏吗?

标签: vue.js vue-composition-api


【解决方案1】:

我不确定,但这就是我在 Vue 组件中保护路线的方式,希望对您有所帮助

 beforeRouteEnter(to, from, next) {
    if (store.getters.isAuthenticated) {
      Promise.all([
        store.dispatch(FETCH_ARTICLE, to.params.slug), 
        store.dispatch(FETCH_COMMENTS, to.params.slug)
      ]).then(() => {
        next();
      });
    } else {
      Promise.all([store.dispatch(FETCH_ARTICLE, to.params.slug)]).then(() => {
        next();
      });
    }
  },

【讨论】:

    【解决方案2】:

    您是否尝试过使用beforeEnter
    这样你可以指定哪些路由将执行你的函数

    喜欢下面的代码:

    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          beforeEnter: (to, from, next) => {
            // ...
          }
        }
      ]
    })
    

    【讨论】: