How can I store data before one page closed in Vue

Viewed 421

so far as I know, if you close or refresh a page,the hook 'beforedestroy' and 'destroyed' in Vue would not be triggered.So maybe I can use

window.onbeforeunload = function() { ... }

And here's the code

mounted() {
            window.onbeforeunload = function() {
                window.localStorage.setItem('form', JSON.stringify(this.form))
            }
        }

However, What I store is undefined. So I think that the instance has been destroyed when the function is called. In this way, this.form can't be accessed.Is there any other way?

3 Answers

You are shadowing this keyword by defining an anonymous function, use an arrow function instead:

window.onbeforeunload = () => {
  window.localStorage.setItem('form', JSON.stringify(this.form))
}

i don't think of any way to store data before a page is closed because it's browsers action i guess you can sotre data each x second which is easy but you can't know when a user closes the page because it cuts the connection between the client/user and the server. So the best solution i can think of is saving data every X second.

Try using vue-persist (a library in vue), unlike the localStorage this will help you to retain the stored values even after the window is closed.

Related