> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Vuex 持久化存储

## 业务需求：

在基于 **vue** 开发 **SPA** 项目时，为了解决页面刷新后数据丢失的问题，我们一般都是将数据存储在 **localstorage** 或 **sessionstorage** 中；当数据需要全局处理统一管理时，我们也会借助于 **vue** 官方提供的 **vuex** 来进行数据的统一管理。

**vuex** 相比 **localstorage** 或 **sessionstorage** 来说，存储数据更安全些。与此同时，**vuex** 也存在一些弊端，当页面刷新后，**vuex** 中 **state** 存储的数据同时也会被更新，**vuex** 中存储的数据不能持久化，需要监听处理来维持 **vuex** 存储的数据状态持久化。

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

## 方案一：[**vuex-persistedstate**](https://github.com/robinvdvleuten/vuex-persistedstate#readme)


```sh [npm]
npm install vuex-persistedstate -S
```

```sh [yarn]
yarn add vuex-persistedstate -S
```

```sh [pnpm]
pnpm add vuex-persistedstate -S
```

```sh [bun]
bun add vuex-persistedstate -S
```

```sh [deno]
deno add npm:vuex-persistedstate -S
```

```javascript title="代码示例"
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**数据的持久化存储

```javascript title="代码示例"
/* 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]
});
```

:::danger 注意事项

- **storage**为存储方式，可选值为 **localStorage**、**sessionStorage** 和 **cookies**；
- **localStorage** 和 **sessionStorage** 两种存储方式可以采用上述代码中的写法，若想采用 **cookies** 坐位数据存储方式，则需要另外一种写法；
- **render** 接收一个函数，返回值为一个对象；返回的对象中的键值对既是要持久化存储的数据；
- 若想持久化存储部分数据，请在 **return** 的对象中采用 **key：value** 键值对的方式进行数据存储，**render** 函数中的参数既为 **state** 对象。

:::

## 方案二：[vuex-persist](https://github.com/championswimmer/vuex-persist#readme)


```sh [npm]
npm install vuex-persist -S
```

```sh [yarn]
yarn add vuex-persist -S
```

```sh [pnpm]
pnpm add vuex-persist -S
```

```sh [bun]
bun add vuex-persist -S
```

```sh [deno]
deno add npm:vuex-persist -S
```

```javascript title="代码示例"
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;
```

## 属性方法

|     **属性值**     |              **数据类型**              |                                                                                    **描述**                                                                                    |
| :-------------: | :--------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|       key       |               string               |                                                        The key to store the state in the storage _**Default: 'vuex'**_                                                       |
|     storage     |          Storage (Web API)         |            localStorage, sessionStorage, localforage or your custom Storage object.Must implement getItem, setItem, clear etc._**Default: window\.localStorage**_            |
|    saveState    |  function(key, state\[, storage])  |                                                If not using storage, this custom function handles saving state to persistence                                                |
|   restoreState  | function(key\[, storage]) => state |                                               If not using storage, this custom function handles retrieving state from storage                                               |
|     reducer     |      function(state) => object     |                                      State reducer. reduces state to only those values you want to save. By default, saves entire state                                      |
|      filter     |    function(mutation) => boolean   | Mutation 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 |
|     modules     |              string\[]             |                                         List of modules you want to persist. (Do not write your own reducer if you want to use this)                                         |
|   asyncStorage  |               boolean              |              Denotes if the store uses Promises (like localforage) or not (you must set this to true when suing something like localforage) _**Default: false**_             |
| supportCircular |               boolean              |                                      Denotes if the state has any circular references to itself (state.x === state)_**Default: false**_                                      |

## 总结

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

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