路由器async beforeEach触发两个路由



我正试图在路由保护中等待异步响应。问题是有两条路线被击中。

当页面加载时,/路由会立即触发,然后是我的目标路由

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

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

在我的日志中,当访问/foo时,我看到两个条目,首先是/,然后是500ms后的/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

我不确定,但这是我在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();
});
}
},

您尝试过使用beforeEnter吗
通过这种方式,您可以指定哪些路线将执行您的功能

像下面的代码一样:

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

最新更新