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

孤街浪徒 提交于 2021-02-05 20:19:12

问题


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

   }
}

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



回答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);



回答3:


Are you using vue-router? I would look into navigation guards. I keep them in mind, but haven't used them myself yet. Here's the documentation on them: https://router.vuejs.org/guide/advanced/navigation-guards.html



来源:https://stackoverflow.com/questions/45293861/how-do-i-warn-a-user-of-unsaved-changes-before-leaving-a-page-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!