什么是 Pinia ?
Pinia 出來這么久了(2019年11月左右),也有很多的質(zhì)量非常不錯(cuò)的文章講解關(guān)于 Pinia 的基本使用方式,這里就不再贅述了。
一句話總結(jié)一下:
方便追蹤與調(diào)試 state,支持 Composition API 定義 store,支持 HMR,支持 Plugin 擴(kuò)展
其核心的 defineStore API,讓我覺得它可以摒棄之前 Vuex 的全局集中狀態(tài)管理的思想,利用 Vue 3 的 Composition 特性,提供隨處按需定義小型 store 的能力。
這讓我們更加容易編寫和管理很多不同模塊的 store,提高代碼可讀性,也讓 store 更容易的擴(kuò)展。
如何持久化?
在某些特定的單頁面應(yīng)用場(chǎng)景下,我們使用常規(guī)的 store 來存儲(chǔ)數(shù)據(jù),很多時(shí)候面臨著刷新就會(huì)被重置,所以,我們急需一個(gè)插件功能來實(shí)現(xiàn)對(duì)某些特定的數(shù)據(jù)進(jìn)行狀態(tài)保持。
這里我們很容易想到可以用 sessionStorage 或者 localStorage 來進(jìn)行相應(yīng)的處理,但是要對(duì)不同的 store 中不同的字段進(jìn)行處理,也是有很大的心智負(fù)擔(dān)。
這里我推薦一款 Pinia 的持久化插件:pinia-plugin-persist
他提供了簡便的使用方式以及靈活的配置方式,下面我就和大家分享一下這款插件的使用方式及實(shí)現(xiàn)原理。
使用方法
install
# npm
npm install pinia-plugin-persist
# yarn
yarn add pinia-plugin-persist
# pnpm
pnpm add pinia-plugin-persist
setup
Vue 2
import Vue from 'vue'
import vueCompositionApi from '@vue/composition-api'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPersist)
Vue.use(vueCompositionApi)
Vue.use(pinia)
Vue 3
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPersist)
Typescript definitions
// tsconfig.ts
{
"compilerOptions": {
"types": [
"pinia-plugin-persist"
]
},
}
Usage
源碼即文檔
export interface PersistStrategy {
key?: string;
storage?: Storage;
paths?: string[];
}
export interface PersistOptions {
enabled: true;
strategies?: PersistStrategy[];
}
declare type Store = PiniaPluginContext['store'];
declare module 'pinia' {
interface DefineStoreOptionsBase<S, Store> {
persist?: PersistOptions;
}
}
1. 基本使用
import { defineStore } from "pinia"
export const useStore = defineStore("YourStore", () => {
const foo = ref("foo")
const bar = ref("bar")
return { foo, bar }
}, {
enabled: true
})
開啟 enabled 之后,默認(rèn)會(huì)對(duì)整個(gè) Store 的 state 內(nèi)容進(jìn)行 sessionStorage 儲(chǔ)存。
2. 進(jìn)階用法
strategies 字段說明:
| 屬性 | 描述 |
|---|---|
| key | 自定義存儲(chǔ)的 key,默認(rèn)是 store.$id |
| storage | 可以指定任何 extends Storage 的實(shí)例,默認(rèn)是 sessionStorage |
| paths | state 中的字段名,按組打包儲(chǔ)存 |
import { defineStore } from "pinia"
export const useStore = defineStore("YourStore", () => {
const foo = ref("foo")
const bar = ref("bar")
return { foo, bar }
}, {
enabled: true,
strategies: [{
// 自定義存儲(chǔ)的 key,默認(rèn)是 store.$id
key: "custom storageKey",
// 可以指定任何 extends Storage 的實(shí)例,默認(rèn)是 sessionStorage
storage: localStorage,
// state 中的字段名,按組打包儲(chǔ)存
paths: ["foo", "bar"]
}]
})
storage 屬性可以使用任何繼承自 Storage 協(xié)議的對(duì)象,自定義存儲(chǔ)對(duì)象也可以,如下 cookiesStorage 為例
import Cookies from 'js-cookie'
const cookiesStorage: Storage = {
setItem (key, state) {
return Cookies.set('accessToken', state.accessToken, { expires: 3 })
},
getItem (key) {
return JSON.stringify({
accessToken: Cookies.getJSON('accessToken'),
})
},
}
export const useStore = defineStore("YourStore", () => {
const foo = ref("foo")
const bar = ref("bar")
const accessToken = ref("xxx")
return { foo, bar, accessToken }
}, {
enabled: true,
strategies: [{
key: "token",
storage: cookiesStorage,
paths: ["accessToken"]
}]
})
源碼解讀
type Store = PiniaPluginContext['store'];
type PartialState = Partial<Store['$state']>;
export const updateStorage = (strategy: PersistStrategy, store: Store) => {
// 默認(rèn)使用 sessionStorage
const storage = strategy.storage || sessionStorage
// 默認(rèn)存儲(chǔ) key 為 store.$id
const storeKey = strategy.key || store.$id
if (strategy.paths) {
// 遍歷 paths 將對(duì)應(yīng)的屬性收集到 finalObj 中
const partialState = strategy.paths.reduce((finalObj, key) => {
finalObj[key] = store.$state[key]
return finalObj
}, {} as PartialState)
// 執(zhí)行存儲(chǔ)
storage.setItem(storeKey, JSON.stringify(partialState))
} else {
// 如果沒有 paths,則按整個(gè) store.$state 存儲(chǔ)
storage.setItem(storeKey, JSON.stringify(store.$state))
}
}
export default ({ options, store }: PiniaPluginContext): void => {
// 判斷插件功能是否開啟
if (options.persist?.enabled) {
// 默認(rèn)策略實(shí)例
const defaultStrat: PersistStrategy[] = [{
key: store.$id,
storage: sessionStorage,
}]
const strategies = options.persist?.strategies?.length ? options.persist?.strategies : defaultStrat
strategies.forEach((strategy) => {
const storage = strategy.storage || sessionStorage
const storeKey = strategy.key || store.$id
const storageResult = storage.getItem(storeKey)
if (storageResult) {
// 如果 storage 中存在同步數(shù)據(jù)
store.$patch(JSON.parse(storageResult))
updateStorage(strategy, store)
}
})
store.$subscribe(() => {
// 監(jiān)聽 state 變化,同步更新 storage
strategies.forEach((strategy) => {
updateStorage(strategy, store)
})
})
}
}
看完源碼之后,發(fā)現(xiàn)功能其實(shí)很簡單,但是其中靈活的 API 設(shè)計(jì)還是讓我眼前一亮,擴(kuò)展性和定制性也得到了的極大的提升,還是非常值得學(xué)習(xí)的一個(gè)插件。
最后
有了持久化存儲(chǔ)的能力,我們就可以更愉快的進(jìn)行數(shù)據(jù)管理啦~
最后附上插件官方文檔地址,不過是純英文的哦