關(guān)于Pinia狀態(tài)持久化問題
Pinia狀態(tài)持久化
在vue3中,常用Pinia代替Vuex來進(jìn)行狀態(tài)管理。這里貼上Pinia的官網(wǎng),有興趣的可以去了解一下。Pinia??
其他過程就省略了,今天在vue3中實現(xiàn)一個最簡單的Pinia持久化插件,后續(xù)可能會進(jìn)一步封裝
// FilePath < @/main.ts > import { createApp, toRaw } from 'vue' import App from './App.vue' // 引入pinia import { createPinia, PiniaPluginContext } from "pinia"; const app = createApp(App) type Options = { key?: string } // 默認(rèn)的key const __piniaKey__: string = 'Ocean' // 負(fù)責(zé)存儲的函數(shù) const setStorage = (key: string, value: any) => { // 將對象轉(zhuǎn)字符串后存入 localStorage localStorage.setItem(key, JSON.stringify(value)) } // 負(fù)責(zé)取值的函數(shù) const getStorage = (key: string) => { // 根據(jù)key拿到localStorage中對應(yīng)的值 return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {} } // Pinia持久化插件 const piniaPlugin = (options: Options) => { return (context: PiniaPluginContext) => { const { store } = context const data = getStorage(`${options?.key ?? __piniaKey__}-${store.$id}`) console.log(data); store.$subscribe(() => { // store.$state是一個 proxy 對象 要通過 toRaw() 轉(zhuǎn)換成 原始對象 setStorage(`${options?.key ?? __piniaKey__}-${store.$id}`,toRaw(store.$state)) }) return { ...data } } } // 創(chuàng)建一個Pinia實例 const store = createPinia() // 注冊插件 store.use(piniaPlugin({ key: 'pinia' })) app.use(store) app.mount('#app')
Pinia數(shù)據(jù)持久化處理
1.下載插件pinia-plugin-persist
2.store下的index.js
import { createPinia } from 'pinia' //pinia 持久化插件 import piniaPluginPersist from 'pinia-plugin-persist' const store = createPinia() store.use(piniaPluginPersist) export default store
在寫的store.js文件下增加配置項 默認(rèn)為sessionStorage
? persist: { ? ? ? ? enabled: true, ? ? ? ? strategies: [ ? ? ? ? ? ? { ? ? ? ? ? ? ? ? key: 'user', ? ? ? ? ? ? ? ? storage: localStorage, ? ? ? ? ? ? ? ? path:[] //可以選擇保存的字段 ?其余的不保存 ? ? ? ? ? ? } ? ? ? ? ] ? ? }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue Element前端應(yīng)用開發(fā)之功能點管理及權(quán)限控制
在一個業(yè)務(wù)管理系統(tǒng)中,如果我們需要實現(xiàn)權(quán)限控制功能,我們需要定義好對應(yīng)的權(quán)限功能點,然后在界面中對界面元素的功能點進(jìn)行綁定,這樣就可以在后臺動態(tài)分配權(quán)限進(jìn)行動態(tài)控制了,權(quán)限功能點是針對角色進(jìn)行控制的,也就是簡稱RBAC(Role Based Access Control)。2021-05-05Vue項目創(chuàng)建首頁發(fā)送axios請求的方法實例
這篇文章主要給大家介紹了關(guān)于Vue項目創(chuàng)建首頁發(fā)送axios請求的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-02-02解決echarts echarts數(shù)據(jù)動態(tài)更新和dataZoom被重置問題
這篇文章主要介紹了解決echarts echarts數(shù)據(jù)動態(tài)更新和dataZoom被重置問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07vue.js動態(tài)數(shù)據(jù)綁定學(xué)習(xí)筆記
這篇文章主要為大家詳細(xì)介紹了vue.js動態(tài)數(shù)據(jù)綁定學(xué)習(xí)筆記,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05Vue3如何根據(jù)搜索框內(nèi)容跳轉(zhuǎn)至本頁面指定位置
在開發(fā)中我們經(jīng)常遇到這樣的需求,根據(jù)要求跳轉(zhuǎn)至本頁面指定位置,這篇文章主要給大家介紹了關(guān)于Vue3如何根據(jù)搜索框內(nèi)容跳轉(zhuǎn)至本頁面指定位置的相關(guān)資料,需要的朋友可以參考下2022-11-11