初用vuex,通过store存储一些共享数据,但是刷新后数据就清空了,所以需要使用本地存储来保存下来。
1.state从localStorage中获取
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
// store刷新后数据会重载 所以用localStorage保存在本地
state:localStorage.getItem("state") ? JSON.parse(localStorage.getItem("state")):{
userList:[], // 数据列表
},
mutations:{
saveUserList(state,data){
// data为index请求传过来的数据 赋给staet里中的userList的
state.userList = data;
}
}
})
2.在APP.vue中添加以下代码
mounted() {
window.addEventListener('unload',this.saveState)
},
methods: {
saveState(){
localStorage.setItem("state",JSON.stringify(this.$store.state))
}
},
也就是说监听unload方法,如果重载页面就把state存入
sessionStorage,然后在需要state的时候从sessionStorage中取值。
前部分转载:https://www.cnblogs.com/hs610/p/10636275.html
实际应用案例:
App.vue
mounted() {
window.addEventListener("unload", this.saveState);
},
methods: {
saveState()