Do something before reload or close in vue.js

2019-05-05 17:41发布

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

beforeDestroy: function() {
  localStorage.setItem('preference', this.preference);
  ...
}

However, neither closing nor reloading the app actually calls this method. How can I make sure this method is called before the app is closed?

1条回答
放我归山
2楼-- · 2019-05-05 18:05

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?";
}

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

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

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

查看更多
登录 后发表回答