Vuex数据持久化

众所周知,Vuex 的数据是存储在内存中的,刷新一下网页这些数据就会丢失。而有些数据我们希望刷新后仍然能够留存,这就需要把数据存储下来。这里就记录一下,使用 localStorage 来持久化 Vuex 中的数据。

实现思路

  1. 因为 state 中的数据理论上只能通过 mutation 来进行更新,所以可以监听 mutation 事件,在每次事件执行后,将此时整个 state 的数据转为字符串后存储进 localStorage。
  2. 在页面初始化 state 时,读取 localStorage 值,重新转为 JSON 后,合并进当前 state。
  3. 这种方法只是一个简单的实现,只适用于简单对象,对复杂对象来说,重新转为 JSON 可能会失去对应的事件和方法,后面可以考虑以其他方式存储。

代码

插件:

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
29
30
31
32
export default (options = {}) => {
const storage = options.storage || (window && window.localStorage);
const key = options.key || "vuex";

// 获取state的值
const getState = (key, storage) => {
const value = storage.getItem(key);
try {
return typeof value !== "undefined" ? JSON.parse(value) : undefined;
} catch (err) {
console.warn(err);
}
return undefined;
};

// 设置state的值
const setState = (key, state, storage) =>
storage.setItem(key, JSON.stringify(state));

return (store) => {
// 初始化时获取数据,如果有的话,把原来的vuex的state替换掉
const data = Object.assign(store.state, getState(key, storage));
if (data) {
store.replaceState(data);
}

// 订阅 store 的 mutation。handler 会在每个 mutation 完成后调用,接收 mutation 和经过 mutation 后的状态作为参数
store.subscribe((mutation, state) => {
setState(key, state, storage);
});
};
};

调用方式:

1
2
3
4
5
import VuexPersist from "@/plugins/VuexPersist";

export default createStore({
plugins: [VuexPersist()],
});