Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  66] [ 6]  / answers: 1 / hits: 30105  / 9 Years ago, wed, december 23, 2015, 12:00:00

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:


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?


More From » vue.js

 Answers
103

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.


[#63962] Monday, December 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amberlykaliac

Total Points: 415
Total Questions: 100
Total Answers: 85

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
amberlykaliac questions
Mon, Sep 28, 20, 00:00, 4 Years ago
Wed, Jul 29, 20, 00:00, 4 Years ago
Sun, Jul 12, 20, 00:00, 4 Years ago
Sun, May 17, 20, 00:00, 4 Years ago
;