• Vuex数据持久化存储


    vuex存储与本地储存(localstorage、sessionstorage)的区别:
    vuex存储在内存,localstorage(本地存储)则以文件的方式存储在本地,永久保存(不主动删除,则一直存在);sessionstorage( 会话存储 ) ,临时保存。localStorage和sessionStorage只能存储字符串类型,对于复杂的对象可以使用ECMAScript提供的JSON对象的stringify和parse来处理

    Vue项目中使用Vuex作为状态管理,相当于全局的变量存储,可以在所有的vue组件中共享数据、动态修改其状态。vuex是单向数据流,存在vuex中的变量都是响应式数据,组件中一般会通过computed来使用store中的状态、且有缓存
    但是当我们去刷新浏览器的时候,store中的状态都会被清空、重新初始化为最初的状态,在某些情况下,我们可能需要将这些状态保存下来,所以这篇来介绍如何让vuex或pinia的状态持久化存储
    要实现持久化存储,简单来说就是将其状态保存到localStorage或者sessionStorage中
    然后在给每个状态默认值的时候就从localStorage或sessionStorage中取就可以了也就是咱们直接手写实现,另外一种方式就是使用第三方插件(vuex-persistedstate或者vuex-persist)

    一、使用sessionStorage或者localStorage存储
    封装类,用sessionStorage举例(写法仅做参考)

    export class SessionUtils {
      static get(key) {
        return JSON.parse(window.sessionStorage.getItem(key))
      }
      static set(key, value) {
        window.sessionStorage.setItem(key, JSON.stringify(value))
      }
      static remove(key) {
        window.sessionStorage.removeItem(key)
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    使用:

    import { SessionUtils } from '@/utils/index.js'
    
    export default {
      namespaced: true,
      state: {
        count: SessionUtils.get('count') || 0
      },
      mutations: {
        UPDATE_COUNT(state, count) {
          state.count++
          SessionUtils.set('count', state.count)
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    修改状态的时候,往session中存储一下,state从 session中取,达到持久化存储的效果
    二、第三方插件
    举例vuex-persistedstate
    1.安装

    npm install vuex-persistedstate --save-dev
    
    • 1

    2.使用

    import Vue from "vue";
    import Vuex from "vuex";
    import test from './modules/test'
    import user from './modules/user'
    // 引入插件
    import createPersistedState from "vuex-persistedstate";
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      modules: {
        test,
        user
      },
      /* vuex数据持久化配置 */
      plugins: [
        createPersistedState({
          // 存储方式:localStorage、sessionStorage、cookies
          storage: window.sessionStorage,
          // 存储的 key 的key值
          key: "store",
          render(state) {
            // 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
            return { ...state };
          }
        })
      ]
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    上面是将所有的store中的state状态都持久化存储了,如果是想只持久化某一个模块的数据,则将上面plugins修改为下面写法

    plugins: [
      createPersistedState({
        // 存储方式:localStorage、sessionStorage、cookies
        storage: window.sessionStorage,
        // 存储的 key 的key值
        key: "store",
        // 只持久化存储user模块的状态
        paths: ['user']
      })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    *注意cookies存储另一种写法

    import createPersistedState from 'vuex-persistedstate'
    import * as Cookies from 'js-cookie'
    
    export default new Vuex.Store({
      // ...
      plugins: [
        createPersistedState({
          storage: {
            getItem: key => Cookies.get(key),
            setItem: (key, value) => Cookies.set(key, value, { expires: 7 }),
            removeItem: key => Cookies.remove(key)
          }
        })
      ]
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    指定需要持久化的state

    import createPersistedState from "vuex-persistedstate"
    const store = new Vuex.Store({
      // ...
      plugins: [
     	createPersistedState({
    	  storage: window.sessionStorage,
    	  reducer(val) {
    	     return {
    		   // 只储存state中的assessmentData
    		   assessmentData: val.assessmentData
    		 }
    	   }
         })
       ]
     })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    关于C2447 “{”: 缺少函数标题(是否是老式的形式表?)
    打字速度单位WPM、KPM定义与计算方法
    11.用户信息——sql语句的使用、Tornado更改用户信息、Tornado上传图片头像
    VPN技术简介
    用GDB调试程序的栈帧
    nginx修改配置文件不生效
    十七、乐观锁和悲观锁(干货版)
    <C++>vector容器在算法题中应用那么广泛,确定不来深入了解一下吗
    【视觉基础篇】15 # 如何用极坐标系绘制有趣图案?
    《安全物联网系统设计》:我强烈建议你给你的物联网系统加一把安全锁
  • 原文地址:https://blog.csdn.net/danruWang/article/details/126361700