结合sessionStorage解决vuex页面刷新数据丢失的问题

将需要保存在vuex中的数据同时保存在sessionStorage中即可:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const state = {
    count: 0,
};

const mutations = {
    increaseCount(state, num) {
        state.count = state.count + num;
        sessionStorage.setItem('count', JSON.stringify(state.count));
    },
    reduceCount(state, num) {
        state.count = state.count - num;
        sessionStorage.setItem('count', JSON.stringify(state.count));
    }
}
// 页面刷新时,会从sessionStorage中重新读取并赋值
for(let key in state) {
    sessionStorage.getItem(key) ? state[key] = sessionStorage.getItem(key) : false;
}
export default new Vuex.Store({
    state,
    mutations
})

 

posted @ 2017-12-13 10:16  code-luyf  阅读(2141)  评论(0编辑  收藏  举报