Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I warn a user of unsaved changes before leaving a page in Vue

I have an UnsavedChangesModal as a component that needs to be launched when the user tries to leave the page when he has unsaved changes in the input fields (I have three input fields in the page).

components: {     UnsavedChangesModal }, mounted() {     window.onbeforeunload = ''; }, methods: {    alertChanges() {     } } 
like image 570
Bargain23 Avatar asked Jul 25 '17 04:07

Bargain23


People also ask

How do you warn a user of unsaved changes before leaving a page?

One solution is to use the beforeunload event in combination with a "dirty" flag, which only triggers the prompt if it's really relevant. var isDirty = function() { return false; } window.

What is keep alive in Vue?

<KeepAlive> is a built-in component that allows us to conditionally cache component instances when dynamically switching between multiple components.

How do I force a Vue refresh page?

You can force-reload components by adding :key="$route. fullPath".

What is emit in Vue?

Vue $emit is a function that lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, it is the best way to trigger certain events.


1 Answers

Assuming you're using vue-router (and you probably should be), then you'll want to use the beforeRouteLeave guard. The documentation even gives an example of this exact situation:

beforeRouteLeave (to, from , next) {   const answer = window.confirm('Do you really want to leave? you have unsaved changes!')   if (answer) {     next()   } else {     next(false)   } } 

That can be added directly right on your component:

components: { ... }, mounted: { ... } methods: { ... }, beforeRouteLeave (to, from, next) { ... } 
like image 138
jpschroeder Avatar answered Oct 04 '22 13:10

jpschroeder