Unirgy
Unirgy

Reputation: 1535

vue-router: Preventing routing on argument change

I'm trying to confirm leaving not saved form route, and if user declines, to cancel changing the route.

It mostly works with

beforeRouteLeave: function (to, from, next) { 
                      if (!confirm('Leaving form')) next(false);
                   }

The problem is with route arguments, like #/form-path?id=5 - changing the id argument does not trigger beforeRouteLeave.

Which hook can I use to prevent navigation on argument change?

Upvotes: 5

Views: 1274

Answers (1)

Rashad Saleh
Rashad Saleh

Reputation: 2847

Dynamic route matching is specifically designed to make different paths or URLs map to the same route or component. Therefor, changing the argument does not technically count as leaving (or changing) the route, therefor beforeRouteLeave rightly does not get fired.

However, I suggest that one can make the component corresponding to the route responsible for detecting changes in the argument. Basically, whenever the argument changes, record the change then reverse it (hopefully reversal will be fast enough that it gets unnoticed by the user), then ask for confirmation. If user confirms the change, then use your record to "unreverse" the change, but if the user does not confirm, then keep things as they are (do not reverse the reverse).

I have not tested this personally and therefor I do not gurantee it to work, but hopefully it would have cleared up any confusion as to which part of the app is responsible for checking what change.

Upvotes: 1

Related Questions