igreka
igreka

Reputation: 350

How to make next(false) in BeforeRouteEnter prevent Vue-Router from navigating to the route?

I am desperately to implement a navigation guard that will prevent users to access an item page if the item doesn't exist, based on the ID provided in route params.

It says in the Vue-Router guide that:

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.

Yet in my component, using next(false) won't prevent the route change, or component rendering. It won't even navigate back as promised in the doc.

beforeRouteEnter(to, from, next) {
    next(false)
    ajaxcall$.subscribe(data => next(vm => vm.setData(data)))

I would have expected that obvious next(false) to work and prevent the component and route from rendering but nope. The ajax call is made and the data is set.

Upvotes: 2

Views: 3540

Answers (1)

Bence Szalai
Bence Szalai

Reputation: 922

"Make sure that the next function is called exactly once in any given pass through the navigation guard." Vue Router - Global Before Guards

You have multiple next() calls.

Also, your ajaxcall$.subscribe() is most likely an async method, so by the time it calls next(vm => vm.setData(data)) the navigation has happened most probably.

You should use await to make sure the information from ajax is available before calling next().

It might not really be a good idea to slow down each page transition with an API call, but that's a different issue...

Upvotes: 1

Related Questions