vuex数据持久化的两种实现方案

作者:下落香樟树 时间:2024-04-30 10:34:48 

目录
  • 业务需求:

  • 方案一:vuex-persistedstate

  • 方案二:vuex-persist

  • 总结

业务需求:

在基于vue开发SPA项目时,为了解决页面刷新后数据丢失的问题,我们一般都是将数据存储在localstorage或sessionstorage中;当数据需要全局处理统一管理时,我们也会借助于vue官方提供的vuex来进行数据的统一管理。vuex相比localstorage或sessionstorage来说,存储数据更安全些。与此同时,vuex也存在一些弊端,当页面刷新后,vuex中state存储的数据同时也会被更新,vuex中存储的数据不能持久化,需要监听处理来维持vuex存储的数据状态持久化。

为解决页面刷新后vuex中存储的数据状态不能持久化的问题,我采取的方案是借助第三方插件工具来实现vuex数据的持久化存储,来解决页面刷新后数据更新的问题。

方案一:vuex-persistedstate

安装插件


yarn add vuex-persistedstate
// 或
npm install --save vuex-persistedstate

使用方法


import Vuex from "vuex";
// 引入插件
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

const state = {};
const mutations = {};
const actions = {};

const store = new Vuex.Store({
state,
mutations,
actions,
 /* vuex数据持久化配置 */
plugins: [
createPersistedState({
     // 存储方式:localStorage、sessionStorage、cookies
storage: window.sessionStorage,
     // 存储的 key 的key值
key: "store",
render(state) {
       // 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
return { ...state };
}
})
]
});

export default store;

vuex中module数据的持久化存储


/* module.js */
export const dataStore = {
 state: {
   data: []
 }
}

/* store.js */
import { dataStore } from './module'

const dataState = createPersistedState({
 paths: ['data']
});

export new Vuex.Store({
 modules: {
   dataStore
 },
 plugins: [dataState]
});

注意事项:

  1. storage为存储方式,可选值为localStorage、sessionStorage和cookies;

  2. localStorage和sessionStorage两种存储方式可以采用上述代码中的写法,若想采用cookies坐位数据存储方式,则需要另外一种写法;

  3. render接收一个函数,返回值为一个对象;返回的对象中的键值对既是要持久化存储的数据;

  4. 若想持久化存储部分数据,请在return的对象中采用key:value键值对的方式进行数据存储,render函数中的参数既为state对象。

方案二:vuex-persist

安装插件


yarn add vuex-persist
// 或
npm install --save vuex-persist

使用方法


import Vuex from "vuex";
// 引入插件
import VuexPersistence from "vuex-persist";

Vue.use(Vuex);
//  初始化
const state = {
userName:'admin'
};
const mutations = {};
const actions = {};
// 创建实例
const vuexPersisted = new VuexPersistence({
storage: window.sessionStorage,
 render:state=>({
 userName:state.userName
   // 或
   ...state
 })
});

const store = new Vuex.Store({
state,
 actions,
 mutations,
 // 数据持久化设置
 plugins:[vuexPersisted.plugins]
});

export default store;

属性方法

属性值数据类型描述
keystringThe key to store the state in the storage_Default: 'vuex'_
storageStorage (Web API)localStorage, sessionStorage, localforage or your custom Storage object.Must implement getItem, setItem, clear etc.Default: window.localStorage
saveStatefunction(key, state[, storage])If not using storage, this custom function handles saving state to persistence
reducerfunction(state) => objectState reducer. reduces state to only those values you want to save. By default, saves entire state
filterfunction(mutation) => booleanMutation filter. Look at mutation.type and return true for only those ones which you want a persistence write to be triggered for. Default returns true for all mutations
modulesstring[]List of modules you want to persist. (Do not write your own reducer if you want to use this)
asyncStoragebooleanDenotes if the store uses Promises (like localforage) or not (you must set this to true when suing something like localforage)Default: false
supportCircularbooleanDenotes if the state has any circular references to it self(state.x === state)Default: false

总结

上述两种方案都可以实现vuex数据持久化存储。方案一是我在实际开发过程中用到的,方案二是在Github上看到的,综合来说,两者都可以时间最终的需求,而且都有对应的案例Demo可以参考。相比来说方案一在GitHub上的start数要高于方案二。

请结合实际情况选择符合自己的方案!

来源:https://juejin.cn/post/6983837431971708965

标签:vuex,数据,持久化
0
投稿

猜你喜欢

  • 利用Opencv中Houghline方法实现直线检测

    2023-09-07 12:40:39
  • Python 常用string函数详解

    2021-01-27 02:59:54
  • SQL Server中使用SQL语句实现把重复行数据合并为一行并用逗号分隔

    2024-01-18 03:06:54
  • Mysql 存储过程中使用游标循环读取临时表

    2024-01-28 00:55:20
  • 解析数据库分页的两种方法对比(row_number()over()和top的对比)

    2024-01-25 08:58:16
  • SQL Server把某个字段的数据用一条语句转换成字符串

    2024-01-13 16:10:12
  • 动态提示的select下拉框

    2007-12-02 14:54:00
  • pytorch DataLoader的num_workers参数与设置大小详解

    2022-12-22 12:15:58
  • Python实现霍夫圆和椭圆变换代码详解

    2022-12-22 19:32:29
  • 树型结构列出指定目录里所有文件的PHP类

    2023-11-17 04:49:04
  • Python用requests-html爬取网页的实现

    2023-03-21 13:24:14
  • Python 常用模块 re 使用方法详解

    2021-02-23 13:10:19
  • zabbix 监控mysql的方法

    2024-01-16 02:11:04
  • Pygame实战之实现经典外星人游戏

    2021-05-10 00:31:44
  • python time模块用法实例详解

    2023-10-09 18:12:50
  • 如何在ADO中使用SQL函数?

    2010-06-17 12:51:00
  • 详解Python中的日志模块logging

    2021-11-24 21:58:34
  • 详解Go 中的时间处理

    2024-02-03 08:26:21
  • Python使用pyinstaller实现学生管理系统流程

    2023-05-25 02:58:05
  • MySQL性能优化之路---修改配置文件my.cnf

    2024-01-23 16:20:53
  • asp之家 网络编程 m.aspxhome.com