vuex+localstorage解决页面刷新时状态丢失的问题

1. utils中增加localStorage.js,封装localstorage方法
var localStorage = window.localStorage

const db = {
	/**
 	 * 更新状态
 	 */
    save (key, value) {
        localStorage.setItem(key, JSON.stringify(value))
    },
    /**
 	 * 获取状态,
 	 * 如果有状态值,获取最新状态值;如果没有,获取默认值
 	 */
    get (key, defaultValue = {}) {
        return JSON.parse(localStorage.getItem(key)) || defaultValue
    },
    /**
 	 * 移除状态
 	 */
    remove (key) {
        localStorage.removeItem(key)
    },
    /**
 	 * 清空状态
 	 */
    clear () {
        localStorage.clear()
    }
}

export default db

2. store的module中,引用localStorage.js
import db from '@/utils/localStorage'

const demo = {
  state: {
    // state1: 5,
    state1: db.get('STATE1', 5),
    // state2: 10,
    state2: db.get('STATE2', 10)
  },

  mutations: {
    SET_STATE1: (state, value) => {
      // state.state1 = value
      db.save('STATE1', value)
    },
    SET_STATE2: (state, value) => {
      // state.state2 = value
      db.save('STATE2', value)
    }
  },

  actions: {
  }
}

export default demo

3. main.js中全局引用localStorage.js
import db from '@/utils/localStorage'
Vue.use(db)
4. vuex正常使用即可

你可能感兴趣的:(vue,localStorage,vue.js,javascript,前端)