vuex-refesh-storage

A Vuex Refesh Storage plugin Typescript

Usage no npm install needed!

<script type="module">
  import vuexRefeshStorage from 'https://cdn.skypack.dev/vuex-refesh-storage';
</script>

README

vuex-refesh-storage

本项目是一个Vuex plugin,用于自动把store中的数据永久存储,例如localStorage、Cookies、localForage。

注意

  1. 关于localForage只是初步这么实现,如果有好的意见可以讨论。
  2. 本项目支持TypeScript

package status GitHub stars npm npm license

package:size npm:size:gzip umd:min:gzip umd:min:brotli

Install

  npm install vuex-refesh-storage -S
  # or yarn
  yarn add vuex-refesh-storage

使用 UMDunpkg:

<script src="https://unpkg.com/vuex-refesh-storage@0.1.0/dist/umd/index.min.js"></script>  

会在全局暴露一个window.VuexRefeshStorage对象。

storage默认会使用window.storage

用法

vuex-refesh-storage (for Vuex# and Vue2)

use JavaScript

  import Vuex from "vuex";
  import VuexRefeshStorage from 'vue-refesh-storage';
  const vuexRefeshStorage = new VuexRefeshStorage()
  // vue 2
  const store = new Vuex.Store({
    plugins: [vuexRefeshStorage.install]
  })

use TypeScript

  import Vuex from "vuex";
  import VuexRefeshStorage from 'vue-refesh-storage';
  const vuexRefeshStorage = new VuexPersistence<RootState>({
    storage: window.localStorage
  })
  // vue 2
  const store = new Vuex.Store<State>({
    plugins: [vuexRefeshStorage.install]
  })

API

初始化参数new VuexRefeshStorage([options])

通过new实例化一个VuexRefeshStorage可以传入一下options定制一些功能。

Property Type Descript
key string 存储持久状态的密钥。默认为vuex。
modules string[] 您要保留的模块列表。(如果要使用此功能,请不要编写自己的reducer)
storage Storage(web API) localStorage, sessionStorage, localforage 或者 自定义 Storage object.
一定要包含 setItem、getItem、clear
Default: window.localStorage
jsonParse JSON:{ stringify, parse } JSON.stringify不能处理循环引用、nullfuntion等等,可以传入自定义的JSON对象。
initStorage Boolean 初始化插件时,是否从storage存储中获取相同key对象;default: true 默认获取。
overwrite Boolean 初始化插件时,从storage存储中获取相同key对象;和当前store.state中的值覆盖或者合并。默认overwrite: true为合并,false覆盖。
deepMergeOptions Object 插件内部使用deepmerge库,当前插件中所有使用deepmerge合并方法可以统一使用deepMergeOptions来配置;默认为{};不了解配置可以看deepmerge options
asyncMode Boolean async:true必须要结合localForage或者其他storage: Promise来使用
filter function (mutation) => boolean store.replaceState时候根据mutation.type来过滤是否触发setState当前值存入storage中。默认不过滤任何mutation
reducer function(state) => object setState的时候会根据modules获取要保存的值。默认不过滤任何值。
getState function(key[, storage]) => state 初始化插件事使用,用于获取storage中的存储。initStoragetrue时使用。
setState function
(key, state[, storage])
存储持久状态的密钥。存储的key为vuex
initAfterFunction function (store) => {} 插件初始化时在store.replaceState更新完成store.state时会调用当前方法。

使用示例

简单使用

使用localstorage来做为永久存储的storage,如果不传入options.storage时,就会默认使用window.localStorage

import { Store } from 'vuex';
import VuexRefeshStorage from 'vuex-refesh-storage';
const vuexRefeshStorage = new VuexRefeshStorage({});
const store = new Store({
  plugin: [vuexRefeshStorage.install]
})

事实上即使是自定义storage对象,只要存在storage.setItemstorage.getItemstoreage.removeItem就可以。

使用sessionStorage

import { Store } from 'vuex';
import VuexRefeshStorage from 'vuex-refesh-storage';
const vuexRefeshStorage = new VuexRefeshStorage({
  storage: sessionStorage
});
const store = new Store({
  plugin: [vuexRefeshStorage.install]
})

使用flatted

如果在state中设置了Circular可以通过传入options.jsonParse来使用定制的转换方法,以flatted为例。

import { Store } from 'vuex';
import flatted from 'flatted';
import VuexRefeshStorage from 'vuex-refesh-storage';
const vuexRefeshStorage = new VuexRefeshStorage({
  jsonParse: flatted
});
const store = new Store({
  plugin: [vuexRefeshStorage.install]
})

结合vuex中的modules

结合store中的modules使用,这是一个比较实用的样例。

vue-cli中结合modules使用。 Edit boring-architecture-huksu

nuxt.js中使用

nuxt中结合modules使用。

store/common/index.js

  import VuexRefeshStorage from 'vuex-refesh-storage'
  export const vuexCommonState = new VuexRefeshStorage({
    key: 'common',
    storage: window.sessionStorage
  })
  export const state = () => ({
    name: 'common'
    nubOnlinecountDown: 0,
    nubOnlineTime: 60,
    currentNow: new Date().getTime()
  })
  export const mutations = {
    setNubOnlinecountDown (state, newValue) {
      state.nubOnlinecountDown = newValue
    }
  }

store/index.js

  import { vuexCommonState } from './common'
  export const plugins = [vuexCommonState.install]

nuxt中可以自动读取store文件下的modules模块并且生成可用的vuex代码。

结合localForage使用

因为WebSQLIndexedDB都是异步操作,它们也可以存入对象、typeArray、ArrayBuffer等等类型。以localForage为例:

window.localStorage为例,传入的storage的对象为以下类型(TypeScript):

// 传入的同步storage类型

interface Storage {
  readonly length: number
  clear(): void
  getItem(key: string): string | null
  key(index: number): string | null
  removeItem(key: string): void
  setItem(key: string, data: string): void
  [key: string]: any
  [index: number]: string
}

如果使用类似于localForage的类型(TypeScript):

  // 传入异步storage类型
  export interface AsyncStorage {
    _config?: {
      name: string
    }
    getItem<T>(key: string, callback?: (err: any, value: T | null) => void): Promise<T | null>;
    setItem<T>(key: string, value: T, callback?: (err: any, value: T) => void): Promise<T>;
    removeItem(key: string, callback?: (err: any) => void): Promise<void>;
    clear(callback?: (err: any) => void): Promise<void>;
    length(callback?: (err: any, numberOfKeys: number) => void): Promise<number>;
    key(keyIndex: number, callback?: (err: any, key: string) => void): Promise<string>;
    keys(callback?: (err: any, keys: string[]) => void): Promise<string[]>;
  }

localForage中的setItem/getItem都可以是异步的操作,在插件初始化的时候并不能保证getItem获取的时机是准确的,所以这里提供了initAfterFunction参数,即使getItem是异步的也可以保证这个方法会在getItem执行完成之后才运行。

如果在使用localForage中的setItemgetItem方法做一些异步定制操作,可以通过重写options.setState/options.getState方法。