清空原因:
刷新页面vuex的数据会丢失属于正常现象,因为JS的数据都是保存在浏览器的堆栈内存里面的,刷新浏览器页面,以前堆栈申请的内存被释放,这就是浏览器的运行机制,那么堆栈里的数据自然就清空了。
解决办法:
1.手动存储
state: {role: localStorage.getItem('role') || '',token: localStorage.getItem('token') || '',
},
actions: {login ({ commit }, { token, role }) {localStorage.setItem('token', token)localStorage.setItem('role', role)commit('setToken', token)commit('setRole', role)}
}
使用localStorage或sessionStorage将vuex存储的数据直接存储在本地。
2.插件存储
本质上是自动存储在localStorage或sessionStorage中。
a.vuex-persistedstate
npm install --save vuex-persistedstate
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'Vue.use(Vuex)export default new Vuex.Store({plugins: [createPersistedState()],state: {},getters: {},mutations: {},actions: {},modules: {}
})
b.vuex-along
npm install vuex-along --save
import VueXAlong from 'vuex-along'Vue.use(Vuex)
const store=new Vuex.Store({modules:{},plugins: [VueXAlong({name: 'along', //存放在localStroage或者sessionStroage 中的名字local: false, //是否存放在local中 false 不存放 如果存放按照下面session的配置配session: { list: [], isFilter: true } //如果值不为false 那么可以传递对象 其中 当isFilter设置为true时, list 数组中的值就会被过滤调,这些值不会存放在seesion或者local中})]})
c.vuex-persist
npm install --save vuex-persist
import VuexPersistence from 'vuex-persist'
Vue.use(Vuex)const vuexLocal = new VuexPersistence({storage: window.localStorage
})const store = new Vuex.Store({modules:{},plugins: [vuexLocal.plugin] })