1. Cause
(1) JS code is run in memory, and all variables and functions during the code run are stored in memory.
(2) Refresh the page, the memory you applied for was released, the script code is reloaded, and the variables must be reassigned.
(3) If you want to not lose data after refreshing, you must store the data externally, such as Local Storage, Session Storage, Index DB, etc. These are APIs provided by the browser, allowing you to store data on your hard drive and perform persistent storage.
2. Two new ways to store data provided by HTML5
localStorage stores data:
(1) The stored data is permanent and never expires;
(2) The scope is limited to the document source level. The same localStorage data is shared between documents of the same origin (regardless of whether the source script actually accesses localStorage).
They can read each other's data and even overwrite each other's data. However, non-homologous documents cannot read or overwrite each other's data. (Even if the scripts they run are from the same third-party server).
sessionStorage stores data:
(1) Session, when the browser is closed, the session ends and the data is cleared, with a time limit;
(2) The validity period of storing data is the same as the top-level window or browser tab page where the script that stores data is located. Once the window or tab page is permanently closed,
Then all data stored through sessionStorage is also deleted.
3. Specific implementation (save the status after login, and remove the status after exit)
// vuex mutations const mutations = { setToken(state, token) { // Save user authentication token ('token', token); = token; }, setUser(state, user) { // Save user information ('user', (user)); = user; }, // Log out and clear token logout(state) { = null; = null; ('token'); ('user'); } }; // vuex getters const getters = { getToken(state){ if( === null){ = ('token') } return ; }, // Get the current user login information getUser(state) { if( === null) { = (('user')); } return ; } };
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.