打赏

页面刷新 vuex 数据重新被初始化

1、原因

vuex里用来存储的也只是一个全局变量,当页面刷新,该全局变量自然不存在了。

2、解决

使用localStorage存储一份

(1)storage.js

/**
 * vuex localStorage plugin
 */
const IS_ALL = 0

export default function storagePlugin({

  namespace = 'mfg-vux-',
  storage = localStorage,
  persistence = []
} = {}) {

  let serialize = JSON.stringify,
    deserialize = JSON.parse,
    isAll = persistence.length === IS_ALL

  /**
   * 获取持久化的state
   * @param  {[type]} state [description]
   * @return {[type]}       [description]
   */
  function getState(state) {

    let data = {},
      keys = isAll ? Object.keys(state) : persistence,
      i = 0,
      len = keys.length

    for (; i < len; i++) {

      let key = keys[i],
        value = deserialize(storage.getItem(namespace + key))

      data[key] = value === null ? state[key] : value
    }

    return data
  }

  /**
   * 持久化state
   * @param  {[type]} state [description]
   */
  function setState(state) {

    let keys = isAll ? Object.keys(state) : persistence,
      i = 0,
      len = keys.length

    for (; i < len; i++) {

      let key = keys[i]

      storage.setItem(namespace + key, serialize(state[key]))
    }
  }

  return store => {

    let state = store.state

    // 初始化state
    store.replaceState(

      _.merge(

        {},
        state,
        getState(state)
      )
    )

    // 持久化state
    store.subscribe((mutation, state) => {

      setState(state)
    })
  }
}

(2)vuex部分代码

import storage from './plugins/storage'
export default new Vuex.Store({

  state,
  mutations,
  getters,
  actions,
  plugins: [storage({

    // 要保存的变量
    persistence: ['testText']
  })],
  strict: process.env.NODE_ENV !== 'production'
})

变量在localestorage中被保存了:

 

posted @ 2018-09-25 10:30  孟繁贵  阅读(3565)  评论(0编辑  收藏  举报
TOP