Skip to content Skip to sidebar Skip to footer

Do Something Before Reload Or Close In Vue.js

I have a Vue.JS application with a beforeDestroy method that I'm trying to use to store some data in local storage before the app closes or is reloaded. Just for reference: beforeD

Solution 1:

What is it that "closes" or "reloads" the app? Is it the user in the browser closing the window and/or refreshing the page?

If that is the case, nothing is "destroyed" and that function won't run.

You would have to define a onbeforeunload function globally:

window.onbeforeunload = function(){
    return"Are you sure you want to close the window?";
}

Then you can save items to local storage inside that function before the return statement.

Note: don't define it inside your beforeDestroy function, because again, that just won't run when you reload the page or navigate away.

Solution 2:

Understand this question is quite old but if I'm out there searching for it, someone else is!

Unfortunately, as far I can tell there is nothing in Vue that can currently hook into before the user reloads the page either via closing, CMD+R, selecting a new URL etc.

The best solution, if it's sensitive data and you really want them to think about what they are doing, you can do the below which is taken from this medium post.

<script>exportdefault {
      data: () => ({
    isEditing: false
  })
  beforeMount() {
    window.addEventListener("beforeunload", this.preventNav)
  },

  methods: {
    preventNav(event) {
      if (!this.isEditing) return
      event.preventDefault()
      event.returnValue = ""
    }
  }
}
</script>

This will at least bring up a dialogue box asking if they are really sure they want to reload the page.

Note the text of the dialogue box cannot be altered. A good description of what is going on with the dialogue box text is contained in this StackOverflow question.

Post a Comment for "Do Something Before Reload Or Close In Vue.js"