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

Bargain23 picture Bargain23 · Jul 25, 2017 · Viewed 17.3k times · Source

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() {

   }
}

Answer

jpschroeder picture jpschroeder · Mar 26, 2018

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) { ... }