Checkout this article : Vue single page application how to retain state data when page refreshes
import Vuex from "vuex"
Vue.use(Vuex)
function storeLocalStore (state) {
window.localStorage.setItem("userMsg",JSON.stringify(state));
}
export default new Vuex.Store({
state: {
username: "Wang Er",
schedulename: "title",
scheduleid: 0,
},
mutations: {
storeUsername (state,name) {
state.username = name
storeLocalStore (state)
},
storeSchedulename (state,name) {
state.schedulename = name
storeLocalStore (state)
},
storeScheduleid (state,id) {
state.scheduleid = Number(id)
storeLocalStore (state)
},
}
Then when the page loads, the data is retrieved from localStorage and placed in vuex, so Wang Er
is atApp.vue of created The following code is written in the hook function:
/ / Read the status information in localStorage when the page loads
localStorage.getItem("userMsg") && this.$store.replaceState(JSON.parse(localStorage.getItem("userMsg")));
/ / Save the information in vuex to localStorage when the page is refreshed
window.addEventListener("beforeunload",()=>{
localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
})