vue3 pinia使用及持久化注冊(cè)
pinia使用
pinia官網(wǎng)地址
https://pinia.web3doc.top/
0.安裝pinia
npm install pinia # 或者使用 yarn yarn add pinia # 或者使用 pnpm pnpm install pinia
1.pinia掛載
在main.ts,引入pinia,進(jìn)行掛載(不錯(cuò)pinia持久化存儲(chǔ)這掛載即可,需要?jiǎng)t使用5.3的方法掛載)
//main.ts import { createApp } from 'vue' // 導(dǎo)入pinia import { createPinia } from "pinia"; const pinia = createPinia(); // 掛載 createApp(App).use(pinia).mount('#app')
2 封裝store
首先,在項(xiàng)目src目錄下新建store文件夾,在文件夾里創(chuàng)建modules文件夾用來存放各種store,然后在modules目錄下新建單個(gè).ts文件,實(shí)現(xiàn)不同的store
提示:目錄結(jié)構(gòu)如下,index.ts是我封裝的持久化存儲(chǔ),參考5.2
// src/store/modules/wxpay.ts import { defineStore } from 'pinia'; interface wxpayState { wxpayInfo: any[]; name: string, age: number, } // 第一個(gè)參數(shù)是應(yīng)用程序中 store 的唯一 id export const wxpayStore = defineStore('wxpay', { state: (): wxpayState => ({ wxpayInfo: [], name: "測(cè)試", age: 22, }), getters: { getwxpayInfo(): any[] { return this.wxpayInfo; }, }, actions: { async getwxpayInfoFromServer() { const wxpayInfo = await getWxList({ page: 1, pageSize: 1000, }); this.wxpayInfo = wxpayInfo.data.data; }, saveName(name: string) { // 修改state中的name this.name = name; }, }, });
2.1 使用pinia
2.1.1 普通
//xxx.vue <template> <div>name:{{store.name}}</div> <div>age:{{store.age}}</div> </template> <script lang="ts" setup> import { wxpayStore } from "@/store/modules/wxpay"; const store = wxpayStore (); </script>
2.1.2 解構(gòu)取值
//xxx.vue <template> <div>name:{{name}}</div> <div>age:{{age}}</div> </template> <script lang="ts" setup> import { wxpayStore } from "@/store/modules/wxpay"; const store = wxpayStore (); // 使用解構(gòu)取值 const { name, age } = store; </script>
2.1.3 響應(yīng)式賦值(推薦)
原因:父組件A中修改了值,子組件B中并不會(huì)改變,使用場(chǎng)景下,我們需要應(yīng)用響應(yīng)式
調(diào)用pinia提供的storeToRefs(相當(dāng)于ref,需要加.value)方法,實(shí)現(xiàn)響應(yīng)式的效果,使用之后,在script調(diào)用變量和方法需要加 .value,
storeToRefs 只會(huì)解構(gòu)出 state 和 getters,而不會(huì)解構(gòu)出 actions。saveName 是一個(gè) action,所以不能通過 storeToRefs 來獲取。
//xxx.vue <template> <div>name:{{name}}</div> <div>age:{{age}}</div> </template> <script setup lang="ts"> import {storeToRefs} from 'pinia' import { wxpayStore } from "@/store/modules/wxpay"; const store = wxpayStore (); const { name, age} = storeToRefs(store); </script>
2.2. 修改state中的數(shù)據(jù)
2.2.1 修改單個(gè)值
<template> <div>name:{{name}}</div> <div>age:{{age}}</div> <Child></Child> <button @click="onEditNameBtn">修改name</button> </template> <script lang="ts" setup> import {storeToRefs} from 'pinia' import { wxpayStore } from "@/store/modules/wxpay"; const store = wxpayStore (); const { name, age} = storeToRefs(store); function onEditNameBtn(){ name.value="xxxx" } </script>
2.2.2 修改多個(gè)值
使用store的$patch方法
//xxx.vue <button @click="onEditBtn">批量修改數(shù)據(jù)</button> // 法一 const patchStore = () => { store.$patch({ name: "xx", age: 10 }); }; // 法二(推薦) const onEditBtn= () => { store.$patch((state) => { state.name='xx' state.age = 11 }) };
2.3.1 重置state
有時(shí)我們修改了多次state里的值,但是在某一步我們想要回到初始值,pinia提供了對(duì)應(yīng)的方法
// xxx.vue <button @click="reset">重置</button> function reset(){ store.$reset() }
3. getters
getters屬性值是一個(gè)對(duì)象,該對(duì)象里面是各種各樣的方法??梢园裧etter想象成Vue中的計(jì)算屬性,它的作用就是返回一個(gè)新的結(jié)果,那么它也是會(huì)被緩存的,就和computed一樣。同vuex中的getters基本一致。
3.1 getters使用及調(diào)用store中的屬性和函數(shù)的方法
當(dāng)前getters調(diào)用store中的其他屬性或者方法
在getters中g(shù)etter相互調(diào)用采用this關(guān)鍵字即可
wxpay.ts getters: { //state:通過state我們可以調(diào)取state中的值并進(jìn)行基礎(chǔ)數(shù)據(jù)操作,然后該方法返回的是一個(gè)新的數(shù)據(jù)。 getAddAge: (state) => { // 返回state中age值,并+1 return state.age + 1; }, getNameAndAge(): string { return this.name + this.getAddAge; // 調(diào)用其它getter }, },
3.2 組件中調(diào)用
<p>getters:{{getNameAndAge}}</p> //解構(gòu)調(diào)用 const store = wxpayStore (); const { name, age,getNameAndAge} = storeToRefs(store);
3.3 組件中調(diào)用時(shí),getters方法中帶參數(shù)
//wxpay.ts getters: { getAddParamsAge: (state) => { return (params:number)=>state.age + 1 + params; }, },
// xxx.vue <p>getters+Params:{{store.getAddParamsAge(50)}}</p>
4. actions使用
介紹:
state和getters屬性都主要是數(shù)據(jù)層面的,并沒有具體的業(yè)務(wù)邏輯代碼,它們兩個(gè)就和我們組件代碼中的data數(shù)據(jù)和computed計(jì)算屬性一樣。那么,如果有業(yè)務(wù)代碼的話,最好就是寫在actions屬性里面,該屬性就和我們組件代碼中的methods相似,用來放置一些處理業(yè)務(wù)邏輯的方法。
actions屬性值同樣是一個(gè)對(duì)象,該對(duì)象里面也是存儲(chǔ)的各種各樣的方法,包括同步方法和異步方法。
4.1 解構(gòu)調(diào)用及普通調(diào)用
storeToRefs 只會(huì)解構(gòu)出 state 和 getters,而不會(huì)解構(gòu)出 actions。saveName 是一個(gè) action,所以不能通過 storeToRefs 來獲取。
//xxx.vue <button @click="store.saveName('測(cè)試')">調(diào)用action中的方法</button> //結(jié)構(gòu)調(diào)用方法 <button @click="saveName('測(cè)試')">調(diào)用action中的方法</button> <script lang="ts" setup> import { storeToRefs } from 'pinia'; import { wxpayStore } from '@/store/modules/wxpay'; // 獲取 store 實(shí)例 const store = wxpayStore(); // 使用 storeToRefs 解構(gòu)出響應(yīng)式引用 const { clientShows, getClientShow } = storeToRefs(store); // 直接引用 actions const { saveName } = store; // 定義一個(gè)方法來編輯名字 function onEditNameBtn() { saveName("xxxx"); } </script>
5. Pinia-plugin-persistedstate 插件做持久化Pinia狀態(tài)處理
pinia-plugin-persistedstate 旨在通過一致的 API 為每個(gè)人和每個(gè)項(xiàng)目中的 Pinia Store 提供持久化存儲(chǔ)。如果你希望保存一個(gè)完整的 Store,或者需要細(xì)?;渲?storage 和序列化的方式,該插件都為你提供了相應(yīng)的功能,并且可以在你想要持久化的 Store 上使用相同的配置。這意味著,通過此插件,你可以將某些狀態(tài)數(shù)據(jù)保存在瀏覽器的localStorage或sessionStorage中,從而確保在頁面刷新或?yàn)g覽器重啟后,這些數(shù)據(jù)仍能被恢復(fù)和保持。
官方文檔地址
https://prazdevs.github.io/pinia-plugin-persistedstate/guide/config.html
當(dāng)使用 { persist: true } 后,以下是基本的默認(rèn)設(shè)置:
存儲(chǔ)介質(zhì) (storage): localStorage。這是默認(rèn)的存儲(chǔ)位置,用于持久化狀態(tài)。
存儲(chǔ)鍵名 (key): store.id。這是默認(rèn)的鍵名,用于在存儲(chǔ)介質(zhì)中引用數(shù)據(jù)。id 是你定義 store 時(shí)提供的唯一標(biāo)識(shí)符。
序列化/反序列化方法 (serializer): 默認(rèn)使用 JSON.stringify 和 JSON.parse 方法。這些方法用于將狀態(tài)轉(zhuǎn)換為字符串以便存儲(chǔ),并在讀取時(shí)將其轉(zhuǎn)換回 JavaScript 對(duì)象。
持久化狀態(tài)路徑 (paths): undefined。這意味著整個(gè) store 的狀態(tài)將被持久化,除非你明確指定哪些路徑應(yīng)該被持久化。
調(diào)試模式 (debug): false。默認(rèn)情況下,調(diào)試模式是關(guān)閉的,錯(cuò)誤不會(huì)輸出到控制臺(tái)。
在恢復(fù)之前和之后的鉤子 (beforeRestore 和 afterRestore): undefined。默認(rèn)情況下,不會(huì)執(zhí)行任何在恢復(fù)數(shù)據(jù)之前或之后的操作。
5.1 安裝插件
npm instal pinia-plugin-persistedstate pnpm install pinia-plugin-persistedstate yarn add pinia-plugin-persistedstate
5.2 添加
之前目錄下的index.ts文件的作用
//src/store/index.ts import type { App } from 'vue'; import { createPinia } from 'pinia'; import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'; const store = createPinia(); store.use(piniaPluginPersistedstate); export function setupStore(app: App<Element>) { app.use(store); } export { store };
5.3 main.ts文件注冊(cè)store(重要)
import { setupStore } from '@/store'; const app = createApp(App) setupStore(app);
其余store 模塊文件正常構(gòu)造即可
// src/store/modules/wxpay.ts import { defineStore } from 'pinia'; interface wxpayState { wxpayInfo: any[]; name: string, age: number, } // 第一個(gè)參數(shù)是應(yīng)用程序中 store 的唯一 id export const wxpayStore = defineStore('wxpay', { state: (): wxpayState => ({ roleInfo: [], name: "測(cè)試", age: 22, }), getters: { getwxpayInfo(): any[] { return this.wxpayInfo; }, }, actions: { async getwxpayInfoFromServer() { const wxpayInfo = await getWxList({ page: 1, pageSize: 1000, }); this.wxpayInfo = wxpayInfo.data.data; }, saveName(name: string) { // 修改state中的name this.name = name; }, }, persist: { //key: 類型:string, 默認(rèn)值:store.$id, 用于引用 storage 中的數(shù)據(jù)的鍵名。隨便起,不重復(fù)即可 key: 'wxpay-xxx-xx', //storage: 類型:StorageLike, 默認(rèn)值:localStorage, 指定數(shù)據(jù)持久化的存儲(chǔ)介質(zhì)。必須具有 getItem 和 setItem 方法。 storage: sessionStorage, //paths: 類型:string[], 默認(rèn)值:undefined, 指定 state 中哪些數(shù)據(jù)需要被持久化。空數(shù)組表示不持久化任何狀態(tài),undefined 或 null 表示持久化整個(gè) state。 paths: ['name', 'age'], //serializer: 類型:Serializer, 默認(rèn)值:JSON.stringify/JSON.parse, 用于指定持久化時(shí)所使用的序列化方法和恢復(fù) Store 時(shí)的反序列化方法。 serializer: { serialize: (state) => JSON.stringify(state), deserialize: (data) => JSON.parse(data), }, //beforeRestore: 類型:(context: PiniaPluginContext) => void, 默認(rèn)值:undefined,在從 storage 中恢復(fù)數(shù)據(jù)之前觸發(fā)的 hook。 beforeRestore: (context) => { // 在恢復(fù)數(shù)據(jù)之前執(zhí)行操作 }, //afterRestore: 類型:(context: PiniaPluginContext) => void, 默認(rèn)值:undefined, 在從 storage 中恢復(fù)數(shù)據(jù)之后觸發(fā)的 hook。 afterRestore: (context) => { // 在恢復(fù)數(shù)據(jù)之后執(zhí)行操作 }, //debug: 類型:boolean, 默認(rèn)值:false, 當(dāng)設(shè)置為 true 時(shí),會(huì)輸出持久化/恢復(fù) Store 時(shí)可能發(fā)生的任何錯(cuò)誤。 debug: true, }, });
5.4 簡(jiǎn)化配置:
persist: true//開啟持久化配置
// src/store/modules/wxpay.ts import { defineStore } from 'pinia'; interface wxpayState { wxpayInfo: any[]; name: string, age: number, } // 第一個(gè)參數(shù)是應(yīng)用程序中 store 的唯一 id export const wxpayStore = defineStore('wxpay', { state: (): wxpayState => ({ roleInfo: [], name: "測(cè)試", age: 22, }), getters: { getwxpayInfo(): any[] { return this.wxpayInfo; }, }, actions: { async getwxpayInfoFromServer() { const wxpayInfo = await getWxList({ page: 1, pageSize: 1000, }); this.wxpayInfo = wxpayInfo.data.data; }, saveName(name: string) { // 修改state中的name this.name = name; }, }, persist: true });
到此這篇關(guān)于vue3 pinia詳細(xì)使用持久化注冊(cè)的文章就介紹到這了,更多相關(guān)vue3 pinia使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文詳解Vue3的watch是如何實(shí)現(xiàn)監(jiān)聽的
watch這個(gè)API大家都很熟悉,今天這篇文章小編來帶你搞清楚Vue3的watch是如何實(shí)現(xiàn)對(duì)響應(yīng)式數(shù)據(jù)進(jìn)行監(jiān)聽的,希望對(duì)大家有一定的幫助2024-11-11Vue中ref、computed與reactive使用頻率現(xiàn)象分析(示例詳解)
這篇文章主要分析了Vue中的ref、computed和reactive三個(gè)響應(yīng)式API的使用頻率和優(yōu)勢(shì),ref適合處理簡(jiǎn)單數(shù)據(jù)類型的響應(yīng)式需求,感興趣的朋友跟隨小編一起看看吧2024-11-11如何使用yarn創(chuàng)建vite項(xiàng)目+vue3
這篇文章主要介紹了如何使用yarn創(chuàng)建vite項(xiàng)目+vue3,詳細(xì)介紹了使用vite創(chuàng)建vue3過程,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-03-03你知道Vue中神奇的$set是如何實(shí)現(xiàn)的嗎?
在日常開發(fā)中,$set的也是一個(gè)非常實(shí)用的API。但是我們知其然更要知其所以然,接下來就跟隨小編一起看一下Vue中的$set是如何實(shí)現(xiàn)的吧2022-12-12VUE+elementui面包屑實(shí)現(xiàn)動(dòng)態(tài)路由詳解
今天小編就為大家分享一篇VUE+elementui面包屑實(shí)現(xiàn)動(dòng)態(tài)路由詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11