vue3 pinia使用及持久化注冊
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,進行掛載(不錯pinia持久化存儲這掛載即可,需要則使用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
首先,在項目src目錄下新建store文件夾,在文件夾里創(chuàng)建modules文件夾用來存放各種store,然后在modules目錄下新建單個.ts文件,實現(xiàn)不同的store
提示:目錄結(jié)構(gòu)如下,index.ts是我封裝的持久化存儲,參考5.2

// src/store/modules/wxpay.ts
import { defineStore } from 'pinia';
interface wxpayState {
wxpayInfo: any[];
name: string,
age: number,
}
// 第一個參數(shù)是應(yīng)用程序中 store 的唯一 id
export const wxpayStore = defineStore('wxpay', {
state: (): wxpayState => ({
wxpayInfo: [],
name: "測試",
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中并不會改變,使用場景下,我們需要應(yīng)用響應(yīng)式
調(diào)用pinia提供的storeToRefs(相當(dāng)于ref,需要加.value)方法,實現(xiàn)響應(yīng)式的效果,使用之后,在script調(diào)用變量和方法需要加 .value,
storeToRefs 只會解構(gòu)出 state 和 getters,而不會解構(gòu)出 actions。saveName 是一個 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 修改單個值
<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 修改多個值
使用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
有時我們修改了多次state里的值,但是在某一步我們想要回到初始值,pinia提供了對應(yīng)的方法
// xxx.vue
<button @click="reset">重置</button>
function reset(){
store.$reset()
}3. getters
getters屬性值是一個對象,該對象里面是各種各樣的方法??梢园裧etter想象成Vue中的計算屬性,它的作用就是返回一個新的結(jié)果,那么它也是會被緩存的,就和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中的值并進行基礎(chǔ)數(shù)據(jù)操作,然后該方法返回的是一個新的數(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)用時,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ù)邏輯代碼,它們兩個就和我們組件代碼中的data數(shù)據(jù)和computed計算屬性一樣。那么,如果有業(yè)務(wù)代碼的話,最好就是寫在actions屬性里面,該屬性就和我們組件代碼中的methods相似,用來放置一些處理業(yè)務(wù)邏輯的方法。
actions屬性值同樣是一個對象,該對象里面也是存儲的各種各樣的方法,包括同步方法和異步方法。
4.1 解構(gòu)調(diào)用及普通調(diào)用
storeToRefs 只會解構(gòu)出 state 和 getters,而不會解構(gòu)出 actions。saveName 是一個 action,所以不能通過 storeToRefs 來獲取。
//xxx.vue
<button @click="store.saveName('測試')">調(diào)用action中的方法</button>
//結(jié)構(gòu)調(diào)用方法
<button @click="saveName('測試')">調(diào)用action中的方法</button>
<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { wxpayStore } from '@/store/modules/wxpay';
// 獲取 store 實例
const store = wxpayStore();
// 使用 storeToRefs 解構(gòu)出響應(yīng)式引用
const { clientShows, getClientShow } = storeToRefs(store);
// 直接引用 actions
const { saveName } = store;
// 定義一個方法來編輯名字
function onEditNameBtn() {
saveName("xxxx");
}
</script>5. Pinia-plugin-persistedstate 插件做持久化Pinia狀態(tài)處理
pinia-plugin-persistedstate 旨在通過一致的 API 為每個人和每個項目中的 Pinia Store 提供持久化存儲。如果你希望保存一個完整的 Store,或者需要細?;渲?storage 和序列化的方式,該插件都為你提供了相應(yīng)的功能,并且可以在你想要持久化的 Store 上使用相同的配置。這意味著,通過此插件,你可以將某些狀態(tài)數(shù)據(jù)保存在瀏覽器的localStorage或sessionStorage中,從而確保在頁面刷新或瀏覽器重啟后,這些數(shù)據(jù)仍能被恢復(fù)和保持。
官方文檔地址
https://prazdevs.github.io/pinia-plugin-persistedstate/guide/config.html
當(dāng)使用 { persist: true } 后,以下是基本的默認設(shè)置:
存儲介質(zhì) (storage): localStorage。這是默認的存儲位置,用于持久化狀態(tài)。
存儲鍵名 (key): store.id。這是默認的鍵名,用于在存儲介質(zhì)中引用數(shù)據(jù)。id 是你定義 store 時提供的唯一標(biāo)識符。
序列化/反序列化方法 (serializer): 默認使用 JSON.stringify 和 JSON.parse 方法。這些方法用于將狀態(tài)轉(zhuǎn)換為字符串以便存儲,并在讀取時將其轉(zhuǎn)換回 JavaScript 對象。
持久化狀態(tài)路徑 (paths): undefined。這意味著整個 store 的狀態(tài)將被持久化,除非你明確指定哪些路徑應(yīng)該被持久化。
調(diào)試模式 (debug): false。默認情況下,調(diào)試模式是關(guān)閉的,錯誤不會輸出到控制臺。
在恢復(fù)之前和之后的鉤子 (beforeRestore 和 afterRestore): undefined。默認情況下,不會執(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文件注冊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,
}
// 第一個參數(shù)是應(yīng)用程序中 store 的唯一 id
export const wxpayStore = defineStore('wxpay', {
state: (): wxpayState => ({
roleInfo: [],
name: "測試",
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, 默認值:store.$id, 用于引用 storage 中的數(shù)據(jù)的鍵名。隨便起,不重復(fù)即可
key: 'wxpay-xxx-xx',
//storage: 類型:StorageLike, 默認值:localStorage, 指定數(shù)據(jù)持久化的存儲介質(zhì)。必須具有 getItem 和 setItem 方法。
storage: sessionStorage,
//paths: 類型:string[], 默認值:undefined, 指定 state 中哪些數(shù)據(jù)需要被持久化??諗?shù)組表示不持久化任何狀態(tài),undefined 或 null 表示持久化整個 state。
paths: ['name', 'age'],
//serializer: 類型:Serializer, 默認值:JSON.stringify/JSON.parse, 用于指定持久化時所使用的序列化方法和恢復(fù) Store 時的反序列化方法。
serializer: {
serialize: (state) => JSON.stringify(state),
deserialize: (data) => JSON.parse(data),
},
//beforeRestore: 類型:(context: PiniaPluginContext) => void, 默認值:undefined,在從 storage 中恢復(fù)數(shù)據(jù)之前觸發(fā)的 hook。
beforeRestore: (context) => {
// 在恢復(fù)數(shù)據(jù)之前執(zhí)行操作
},
//afterRestore: 類型:(context: PiniaPluginContext) => void, 默認值:undefined, 在從 storage 中恢復(fù)數(shù)據(jù)之后觸發(fā)的 hook。
afterRestore: (context) => {
// 在恢復(fù)數(shù)據(jù)之后執(zhí)行操作
},
//debug: 類型:boolean, 默認值:false, 當(dāng)設(shè)置為 true 時,會輸出持久化/恢復(fù) Store 時可能發(fā)生的任何錯誤。
debug: true,
},
});5.4 簡化配置:
persist: true//開啟持久化配置
// src/store/modules/wxpay.ts
import { defineStore } from 'pinia';
interface wxpayState {
wxpayInfo: any[];
name: string,
age: number,
}
// 第一個參數(shù)是應(yīng)用程序中 store 的唯一 id
export const wxpayStore = defineStore('wxpay', {
state: (): wxpayState => ({
roleInfo: [],
name: "測試",
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詳細使用持久化注冊的文章就介紹到這了,更多相關(guān)vue3 pinia使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue使用 onMounted 確保在組件掛載后執(zhí)行異步操作示例詳解
在 Vue.js 或其他類似框架中,使用 onMounted 是為了確保在組件掛載后執(zhí)行異步操作,這篇文章主要介紹了Vue使用onMounted確保在組件掛載后執(zhí)行異步操作,需要的朋友可以參考下2023-06-06
vue+element樹組件 實現(xiàn)樹懶加載的過程詳解
這篇文章主要介紹了vue+element樹組件 實現(xiàn)樹懶加載的過程,本文通過圖文實例代碼相結(jié)合給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
vue頁面不能根據(jù)路徑進行跳轉(zhuǎn)的解決方法
本文主要介紹了vue頁面不能根據(jù)路徑進行跳轉(zhuǎn)的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-12-12
淺談vue-props的default寫不寫有什么區(qū)別
這篇文章主要介紹了淺談vue-props的default寫不寫有什么區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

