vue-router: Preventing routing on argument change

假装没事ソ 提交于 2019-12-23 10:00:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41435612/vue-router-preventing-routing-on-argument-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!