使用 vuex-persist 持久 Vuex 状态

Vuex非常适合在你的应用程序中处理状态,但有时你想要它在多个页面负载中持续下去,而不是什么。这样做的天真方法(和我一样有罪)是在每个突变中添加一个快速的小函数呼叫,以便将你的应用程序的当前状态保存到localStorage。 不是一个很好的解决方案,但只是不够糟糕,这往往是足够的。 但有更好的方法。 Vuex实际上有插件支持,并且 vuex-persist是一个小小的插件,自动同步你的商店与localStorage,或任何其他存储方法支持Iget/Item/Item/clear界面。

安装

在您的 Vue.js 项目中安装 vuex-persist。

1# Yarn
2$ yarn add vuex-persist
3# or NPM
4$ npm install vuex-persist --save

使用

现在,无论您在何处初始化您的商店(这可能因项目而异),请导入vuex persist并将其初始化为Vuex的插件。

 1[label main.js (Partial)]
 2import Vue from 'vue'
 3import App from 'App.vue';
 4import Vuex 'vuex';
 5import VuexPersist from 'vuex-persist';
 6
 7Vue.use(Vuex);
 8
 9const vuexLocalStorage = new VuexPersist({
10  key: 'vuex' // The key to store the state on in the storage provider.
11  storage: window.localStorage, // or window.sessionStorage or localForage
12  // Function that passes the state and returns the state with only the objects you want to store.
13  // reducer: state => state,
14  // Function that passes a mutation and lets you decide if it should update the state in localStorage.
15  // filter: mutation => (true)
16})
17
18const store = new Vuex.Store({
19  ...
20  plugins: [vuexLocalStorage.plugin]
21});
22
23...
24
25new Vue({
26  store,
27  el: '#app',
28  render: h => h(App)
29});

使用减量选项。

减少器选项允许您仅存储状态的某些部分. 这是一个简单的函数,它通过了完整的状态树,并预计会返回包含您想要保留的状态树的部分的对象。

1const vuexLocalStorage = new VuexPersist({
2  storage: window.localStorage, // or window.sessionStorage or localForage instance.
3  // Function that passes the state and returns the state with only the objects you want to store.
4  reducer: state => ({
5    keepThisModule: state.keepThisModule,
6    keepThisModuleToo: state.keepThisModuleToo
7    // getRidOfThisModule: state.getRidOfThisModule (No one likes it.)
8  })
9})

使用过滤器选项。

有时某些突变不应该触发商店同步,例如,如果您每隔几毫秒出现一个被称为突变,每次被呼叫时更新存储将导致性能的巨大下降。

 1const badMutations = [
 2  'someMutationThatGetsCalledTooOften'
 3]
 4
 5const vuexLocalStorage = new VuexPersist({
 6  storage: window.localStorage, // or window.sessionStorage or localForage
 7  // Function that passes the state and returns the state with only the objects you want to store.
 8  // someMutationThatGetsCalledTooOften gets ignored
 9  filter: mutation => (badMutations.indexOf(mutation.type) === -1) // Boolean
10})
Published At
Categories with 技术
Tagged with
comments powered by Disqus