I have a Vue component that is monitoring whether it has unsaved changes. I want to alert the user before they move away from the current form if there are unsaved modifications. In a traditional web application, you could use onbeforeunload
. I tried implementing it in the mounted hook like this:
mounted: function(){
window.onbeforeunload = function() {
return self.form_dirty ? "If you leave this page, your unsaved changes will be lost." : null;
}
}
However, this approach does not work when using Vue Router. It allows navigation through router links without warning, but triggers the alert when attempting to close the window or go to an external link.
Is there a way to simulate the behavior of onbeforeunload
in a Vue application for both regular links and router links?