1. Pinia 的介紹
狀態(tài)管理是現(xiàn)代 Web 應(yīng)用開發(fā)中的一個(gè)重要概念。Vue 3 中的狀態(tài)管理庫 Pinia
,是一個(gè)基于Vue 3 Composition API
的狀態(tài)管理庫,它提供了一種簡(jiǎn)單、靈活的方式來管理應(yīng)用程序的狀態(tài),同時(shí)還具有高性能和可擴(kuò)展性。Pinia
在某種程度上來說,也可以被叫做Vuex5
,因?yàn)樗Y(jié)合了Vuex 5
核心團(tuán)隊(duì)討論中的許多想法,所以 Pinia
被作為新的推薦方案來代替Vuex
。
2. Pinia 的優(yōu)點(diǎn)
-
Devtools 支持
- 追蹤
actions
、mutations
的時(shí)間線 - 在組件中展示它們所用到的
Store
- 讓調(diào)試更容易的
Time travel
- 追蹤
-
熱更新
- 不必重載頁面即可修改
Store
- 開發(fā)時(shí)可保持當(dāng)前的
State
- 不必重載頁面即可修改
-
直接通過
actions
修改state
中的數(shù)據(jù)。廢棄了mutation
。 -
不再有可命名的模塊。取消了
vuex
中的module
,每個(gè)Pinia
模塊都是獨(dú)立的 -
插件。可通過插件擴(kuò)展
Pinia
功能 -
更好的
TypeScript
支持。提供了代碼補(bǔ)全功能,避免了過多魔法字符串的注入。 - 支持服務(wù)端渲染。
- 體積更小。壓縮后只有2.1KB
3. Pinia 的安裝和使用
3.1. 安裝
安裝 Pinia 很簡(jiǎn)單,只需要使用 npm 或者 yarn 安裝即可:
npm install pinia
# 或
yarn add pinia
3.2. 使用
3.1.1. 創(chuàng)建一個(gè) Pinia Store
創(chuàng)建一個(gè) Pinia Store 非常簡(jiǎn)單,下面是一個(gè)簡(jiǎn)單的示例:Tips
: 關(guān)于 Pinia Store 的命名,官方推薦的做法是 use+名稱+Store。
import { defineStore } from 'pinia'
// 你可以對(duì) `defineStore()` 的返回值進(jìn)行任意命名,但最好使用 store 的名字,同時(shí)以 `use` 開頭且以 `Store` 結(jié)尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一個(gè)參數(shù)是你的應(yīng)用中 Store 的唯一 ID。
export const useCounterStore = defineStore({
id: "counter",
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
getters: {
doubleCount: ({ count }) => count * 2,
},
});
在上面的代碼中,我們首先使用 defineStore
函數(shù)創(chuàng)建了一個(gè)名為 useCounterStore
的 Pinia Store,然后在 state
函數(shù)中定義了一個(gè) count
屬性,最后在 actions
對(duì)象中定義了 increment
和 decrement
兩個(gè)方法來修改 count
屬性。
當(dāng)然了,我們用一個(gè)函數(shù)來定義 Store 也是同樣可行的:
import { ref, computed } from "vue";
// 你可以對(duì) `defineStore()` 的返回值進(jìn)行任意命名,但最好使用 store 的名字,同時(shí)以 `use` 開頭且以 `Store` 結(jié)尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一個(gè)參數(shù)是你的應(yīng)用中 Store 的唯一 ID。
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++
}
function decrement() {
count.value--
}
return { count, doubleCount, increment, decrement }
})
3.2.2. 在組件中使用 Pinia Store
要在組件中使用 Pinia Store,我們需要將 Store 導(dǎo)入進(jìn)來。
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter";
const counterStore = useCounterStore()
// 注意此處不能直接采用結(jié)構(gòu)賦值的方法:如 const { count, doubleCount } = useCounterStore()
// 這樣會(huì)讓數(shù)據(jù)失去響應(yīng)性
</script>
想結(jié)構(gòu)賦值的話,需要導(dǎo)入 storeToRefs 函數(shù),將解構(gòu)出來的參數(shù)變成響應(yīng)式:
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useCounterStore } from "@/stores/counter";
const counterStore = useCounterStore()
// 將解構(gòu)出來的參數(shù)變成響應(yīng)式
const { count, doubleCount } = storeToRefs(counterStore)
// 作為 action 的 increment 和 decrement 可以直接解構(gòu)
const { increment, decrement } = counterStore
</script>
3.2.3. 在模板中使用 Pinia Store
要在模板中使用 Pinia Store,我們?cè)谀0逯兄苯邮褂镁托辛恕?/p>
<template>
<div>
<p>Count: {{ counterStore.count }}</p>
<p>doubleCount: {{ counterStore.doubleCount }}</p>
<button @click="counterStore.increment()">Increment</button>
<button @click="counterStore.decrement()">Decrement</button>
</div>
</template>
4. Pinia 的狀態(tài)管理和數(shù)據(jù)流
-
在
Pinia
中,狀態(tài)管理和數(shù)據(jù)流的概念非常重要。狀態(tài)管理是指將應(yīng)用程序的狀態(tài)保存在一個(gè)中心化的地方,并通過一些方法來修改和查詢狀態(tài)。數(shù)據(jù)流是指數(shù)據(jù)在應(yīng)用程序中的流動(dòng)方式,包括數(shù)據(jù)的來源、傳輸、處理和存儲(chǔ)等方面。 -
在
Pinia
中,我們可以使用Store
來管理應(yīng)用程序的狀態(tài),并使用Actions
和Getters
來修改和查詢狀態(tài)。Store
是一個(gè)包含狀態(tài)、Actions 和 Getters 的對(duì)象,它可以被多個(gè)組件共享。當(dāng)一個(gè)組件需要修改或查詢狀態(tài)時(shí),它可以通過Store
來訪問狀態(tài),并調(diào)用相應(yīng)的Actions
或Getters
來修改或查詢狀態(tài)。 -
在
Pinia
中,數(shù)據(jù)的流動(dòng)方式非常簡(jiǎn)單和直觀。當(dāng)一個(gè)組件調(diào)用Store
中的Actions
來修改狀態(tài)時(shí),數(shù)據(jù)會(huì)從組件流向Store
,然后從Store
再流向其他組件。當(dāng)一個(gè)組件調(diào)用Store
中的Getters
來查詢狀態(tài)時(shí),數(shù)據(jù)會(huì)從Store
流向組件。這種數(shù)據(jù)流的方式非常清晰和可控,使得我們可以更好地管理和維護(hù)應(yīng)用程序的狀態(tài)。
5. Pinia 的模塊化和命名空間
在 Pinia 中,我們可以使用模塊化和命名空間來組織 Store,以便更好地管理和維護(hù)應(yīng)用程序的狀態(tài)。模塊化和命名空間可以幫助我們將應(yīng)用程序的狀態(tài)分成多個(gè)邏輯模塊,并將其組合成完整的應(yīng)用程序狀態(tài)。這種模塊化和命名空間的方式非常清晰和可控,使得我們可以更好地管理和維護(hù)應(yīng)用程序的狀態(tài)。
5.1. 模塊化
在 Pinia 中,我們可以使用 defineStore
函數(shù)來定義一個(gè) Store。defineStore
函數(shù)可以接受一個(gè)參數(shù)對(duì)象,其中包含了 Store 的狀態(tài)、Actions 和 Getters 等信息。我們可以將多個(gè) defineStore
函數(shù)組合成一個(gè)完整的 Store,以便更好地管理和維護(hù)應(yīng)用程序的狀態(tài)。
import { defineStore } from 'pinia'
const counterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
},
getters: {
doubleCount: (state) => state.count * 2,
},
})
const userStore = defineStore({
id: 'user',
state: () => ({
name: '',
email: ''
}),
actions: {
setName(name) {
this.name = name
},
setEmail(email) {
this.email = email
}
}
})
export default {
counterStore,
userStore
}
在上面的代碼中,我們首先使用 defineStore
函數(shù)定義了一個(gè)名為 counterStore
的 Store,其中包含了計(jì)數(shù)器狀態(tài)和增加和減少計(jì)數(shù)器值的 Actions。然后,我們又使用 defineStore
函數(shù)定義了一個(gè)名為 userStore
的 Store,其中包含了用戶信息狀態(tài)和修改用戶名和電子郵件的 Actions。最后,我們將 counterStore
和 userStore
導(dǎo)出為一個(gè)對(duì)象,以便在其他組件中使用。
5.2. 命名空間
在 Pinia 中,我們可以使用命名空間來組織 Store。命名空間可以將多個(gè) Store 分組,并將其組合成完整的應(yīng)用程序狀態(tài)。命名空間可以幫助我們更好地管理和維護(hù)應(yīng)用程序的狀態(tài),避免了狀態(tài)沖突和重復(fù)定義的問題。
import { createPinia } from 'pinia'
import { counterStore } from './counter'
import { userStore } from './user'
const pinia = createPinia()
pinia.useStore('counter', counterStore)
pinia.useStore('user', userStore)
export default pinia
在上面的代碼中,我們首先使用 createPinia
函數(shù)創(chuàng)建了一個(gè) Pinia 實(shí)例,然后使用 useStore
函數(shù)將 counterStore
和 userStore
添加到了 Pinia 實(shí)例中,并分別使用了 counter
和 user
命名空間。這意味著,在其他組件中,我們可以通過 this.$pinia.store.counter
和 this.$pinia.store.user
來訪問計(jì)數(shù)器 Store 和用戶信息 Store。
6. Pinia 的插件機(jī)制和異步操作
6.1. 插件機(jī)制
在 Pinia 中,我們可以使用插件來擴(kuò)展其功能。插件可以是一個(gè)簡(jiǎn)單的對(duì)象,也可以是一個(gè)包含多個(gè)函數(shù)的對(duì)象。我們可以使用 use
函數(shù)來添加插件。
import { createPinia } from 'pinia'
const pinia = createPinia()
const myPlugin = {
// ...
}
pinia.use(myPlugin)
在上面的代碼中,我們首先使用 createPinia
函數(shù)創(chuàng)建了一個(gè) Pinia 實(shí)例,然后使用 use
函數(shù)將 myPlugin
添加到了 Pinia 實(shí)例中。
6.2. 異步操作
在 Pinia 中,我們可以使用異步操作來處理一些需要等待的數(shù)據(jù)。異步操作可以是一個(gè) Promise,也可以是一個(gè)異步函數(shù)。我們可以使用 await
關(guān)鍵字來等待異步操作的結(jié)果。文章來源:http://www.zghlxwxcb.cn/news/detail-467642.html
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
name: '',
email: ''
}),
actions: {
async fetchUser() {
const response = await fetch('/api/user')
const data = await response.json()
this.name = data.name
this.email = data.email
}
}
})
在上面的代碼中,我們首先使用 defineStore
函數(shù)定義了一個(gè)名為 useUserStore
的 Store,其中包含了用戶信息狀態(tài)和異步獲取用戶信息的 fetchUser
方法。在 fetchUser
方法中,我們首先使用 fetch
函數(shù)獲取用戶信息的數(shù)據(jù),然后使用 await
關(guān)鍵字等待 fetch
函數(shù)的結(jié)果,并將其解析為 JSON 格式。最后,我們將獲取的數(shù)據(jù)賦值給 Store 的狀態(tài)。文章來源地址http://www.zghlxwxcb.cn/news/detail-467642.html
到了這里,關(guān)于vue 3 第三十一章:狀態(tài)管理(Pinia基礎(chǔ)知識(shí))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!