1:设置state为null,然后在对应的getters里面添加sessionStorage控制,在mutations里面添加对应sessionStorage控制,如:
let _store = { state: { appType: null }, getters: { appType(state){ if(!state.appType) { state.appType = getSessionStorage("appType") } return state.appType } }, mutations: { setAppType (state, appType) { state.appType = appType setSessionStorage("appType",appType) } } };
缺点:必须为state设置为null,并且必须为每一个getters添加sessionStorage控制,比较繁琐
2:在页面初始化的时候,取出所有的保存在sessionStorage里面的值,同时在页面刷新前,将所有的state保存在sessionStorage里面
//在页面加载时读取sessionStorage里的状态信息 if (sessionStorage.getItem("store") ) { this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store")))) } //在页面刷新时将vuex里的信息保存到sessionStorage里 window.addEventListener("beforeunload",()=>{ sessionStorage.setItem("store",JSON.stringify(this.$store.state)) })
缺点:beforeunload在移动端有兼容性问题