zoukankan      html  css  js  c++  java
  • 页面刷新 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中被保存了:

  • 相关阅读:
    HTTPS证书撤销
    前端跨域问题解析
    js递归遍历key
    阿里云centos配置nginx和nodejs
    Linux 查看服务器配置
    解决IPOD NANO7无法开机
    GIF添加3D加速
    关于bootstrap Modal弹窗 滚动条的问题
    Just-In-Time Debugging in Visual Studio 禁止VS在服务器上调试
    利用ASP.NET操作IIS (可以制作安装程序)
  • 原文地址:https://www.cnblogs.com/mengfangui/p/9698263.html
Copyright © 2011-2022 走看看