Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 895
Unirgy Avatar asked Nov 08 '22 03:11

Unirgy


1 Answers

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.

like image 98
Rashad Saleh Avatar answered Nov 14 '22 22:11

Rashad Saleh