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

32,029

Solution 1

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

Solution 2

These answers only cover navigation within Vue. If the user refreshes the page or navigates to a different site, that will not be caught. So you also need something like:

window.onbeforeunload = () => (this.unsavedChanges ? true : null);
Share:
32,029
Bargain23
Author by

Bargain23

Updated on April 28, 2020

Comments

  • Bargain23
    Bargain23 about 4 years

    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() {
    
       }
    }
    
  • Ziad Akiki
    Ziad Akiki over 5 years
    Does this works when navigating to another website / closing the browser tab as well?
  • James Hall
    James Hall over 5 years
    @ZiadAkiki it doesn't block them for me no.
  • PirateApp
    PirateApp over 5 years
    upvoted! what to do if I am not using the Vue router
  • jpschroeder
    jpschroeder over 5 years
    If you aren't using vue router then youll have to just bind to the window with: window.onbeforeunload = () => 'Are you sure you want to leave?'
  • NewTech Lover
    NewTech Lover almost 4 years
    @jpschroeder how can be it used for such a scenario? Let's say you have a route /settings/:productId then made changes for that selected product and from drop down tried to to select another product then how can dialog be implemented in this case? Since only id was changed. Because above solution didn't work.
  • ap.singh
    ap.singh over 3 years
    But how we are going to use this in vue.js. Can you please five an example
  • Error - Syntactical Remorse
    Error - Syntactical Remorse about 3 years
    If anyone else reads this and wants a working Vue example see this answer.
  • Error - Syntactical Remorse
    Error - Syntactical Remorse about 3 years
    If anyone else reads this and wants a working Vue example which works even when closing the page. See this answer
  • pavan kumar
    pavan kumar about 3 years
    @NewTechLover you can handle using "beforeRouteUpdate" method for dynamic route params