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

前端 未结 3 1436
天命终不由人
天命终不由人 2021-02-02 09:28

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

相关标签:
3条回答
  • 2021-02-02 09:46

    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);
    
    0 讨论(0)
  • 2021-02-02 09:54

    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

    0 讨论(0)
  • 2021-02-02 10:03

    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) { ... }
    
    0 讨论(0)
提交回复
热议问题