1

I am using Vue.js. I have a component where the user can save data. But it is possible that user has not saved the data and he tries to navigate to other route or destroy the component. I want to show a message that there is unsaved data and user really wants to leave it unsaved.

If the user says that he does not want to leave the unsaved data, then I have to stop navigation or component's destroying. I am using beforeDestroy to check if there is unsaved data and it works but I can not stop destroying the component or navigation. I tried using beforeRouteLeave but it does not work. Any ideas on how to make this work?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rohanil
  • 1,717
  • 5
  • 22
  • 47
  • try https://stackoverflow.com/questions/40425682/disable-changes-you-made-may-not-be-saved-pop-up-window – Daksh M. Dec 22 '17 at 13:48
  • @DakshMiglani its not about only `stopping user` its about stoping when user route to next component , please read question properly and suggest answer. – Hardik Satasiya Dec 22 '17 at 14:52

1 Answers1

1

Hmm I see, are you sure using beforeRouteLeave in this manner

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

key is next(false)

you need to pass false as argument in next() so it will not forward to next route.

just need to check if its correctly used.

Hardik Satasiya
  • 9,547
  • 3
  • 22
  • 40
  • yea, using exactly same code. my route's component is not the component where I am doing this. I am doing it in child component of route component. Does it make any difference? – Rohanil Dec 22 '17 at 14:32
  • can you do `console.log(to, from);` inside beforeRouteLeave when you try to navigate away, and share its value. – Hardik Satasiya Dec 22 '17 at 14:37
  • I added `beforeRouteLeave` in route's component and it is being called there. Previously, it was never being even called when I had it in child component. But now, there is another problem. The child component's `beforeDestroy` is being executed later than route component's `beforeRouteLeave`. So my route component doesn't know if there is unsaved data in child component. – Rohanil Dec 22 '17 at 15:04
  • from document i can see that you have access to `this` <- `current vm` so you can access all the details of current component and check there is unsaved data or not. – Hardik Satasiya Dec 22 '17 at 15:21