
前言
Pinia ,發音為 /pi?nj?/,來源于西班牙語 pi?a 。意思為菠蘿,表示與菠蘿一樣,由很多小塊組成。在 Pinia 中,每個 Store 都是單獨存在,一同進行狀態管理。
Pinia 是由 Vue.js 團隊成員開發,最初是為了探索 Vuex 下一次迭代會是什么樣子。過程中,Pinia 實現了 Vuex5 提案的大部分內容,于是就取而代之了。
與 Vuex 相比,Pinia 提供了更簡單的 API,更少的規范,以及 Composition-API 風格的 API 。更重要的是,與 TypeScript 一起使用具有可靠的類型推斷支持。
Pinia 與 Vuex 3.x/4.x 的不同
- mutations 不復存在。只有 state 、getters 、actions。
- actions 中支持同步和異步方法修改 state 狀態。
- 與 TypeScript 一起使用具有可靠的類型推斷支持。
- 不再有模塊嵌套,只有 Store 的概念,Store 之間可以相互調用。
- 支持插件擴展,可以非常方便實現本地存儲等功能。
- 更加輕量,壓縮后體積只有 2kb 左右。
既然 Pinia 這么香,那么還等什么,一起用起來吧!
基本用法
安裝:
在 main.js 中 引入 Pinia:
// src/main.js
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
定義一個 Store
在 src/stores 目錄下創建 counter.js 文件,使用 defineStore() 定義一個 Store 。defineStore() 第一個參數是 storeId ,第二個參數是一個選項對象:
// src/stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () ({ count: 0 }),
getters: {
doubleCount: (state) state.count * 2
},
actions: {
increment() {
this.count++
}
}
})
我們也可以使用更高級的方法,第二個參數傳入一個函數來定義 Store :
// src/stores/counter.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () {
const count = ref(0)
const doubleCount = computed(() count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
在組件中使用
在組件中導入剛才定義的函數,并執行一下這個函數,就可以獲取到 store 了:
<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
// 以下三種方式都會被 devtools 跟蹤
counterStore.count++
counterStore.$patch({ count: counterStore.count + 1 })
counterStore.increment()
</script>
<template>
<div>{{ counterStore.count }}</div>
<div>{{ counterStore.doubleCount }}</div>
</template>
這就是基本用法,下面我們來介紹一下每個選項的功能,及插件的使用方法。
State
解構 store
store 是一個用 reactive 包裹的對象,如果直接解構會失去響應性。我們可以使用 storeToRefs() 對其進行解構:
<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
const { count, doubleCount } = storeToRefs(counterStore)
</script>
<template>
<div>` count `</div>
<div>` doubleCount `</div>
</template>
修改 store
除了可以直接用 store.count++ 來修改 store,我們還可以調用 $patch 方法進行修改。$patch 性能更高,并且可以同時修改多個狀態。
<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
counterStore.$patch({
count: counterStore.count + 1,
name: 'Abalam',
})
</script>
但是,這種方法修改集合(比如從數組中添加、刪除、插入元素)都需要創建一個新的集合,代價太高。因此,$patch 方法也接受一個函數來批量修改:
cartStore.$patch((state) {
state.items.push({ name: 'shoes', quantity: 1 })
state.hasChanged = true
})
監聽 store
我們可以通過 $subscribe() 方法可以監聽 store 狀態的變化,類似于 Vuex 的 subscribe 方法。與 watch() 相比,使用 $subscribe() 的優點是,store 多個狀態發生變化之后,回調函數只會執行一次。
<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
counterStore.$subscribe((mutation, state) => {
// 每當狀態發生變化時,將 state 持久化到本地存儲
localStorage.setItem('counter', JSON.stringify(state))
})
</script>
也可以監聽 pinia 實例上所有 store 的變化。
// src/main.js
import { watch } from 'vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
watch(
pinia.state,
(state) => {
// 每當狀態發生變化時,將所有 state 持久化到本地存儲
localStorage.setItem('piniaState', JSON.stringify(state))
},
{ deep: true }
)
Getters
訪問 store 實例
大多數情況下,getter 只會依賴 state 狀態。但有時候,它會使用到其他的 getter ,這時候我們可以通過 this 訪問到當前 store 實例。
// src/stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () ({ count: 0 }),
getters: {
doubleCount(state) {
return state.count * 2
},
doublePlusOne() {
return this.doubleCount + 1
}
}
})
訪問其他 Store 的 getter
要使用其他 Store 的 getter,可以直接在 getter 內部使用:
// src/stores/counter.js
import { defineStore } from 'pinia'
import { useOtherStore } from './otherStore'
export const useCounterStore = defineStore('counter', {
state: () ({
count: 1
}),
getters: {
composeGetter(state) {
const otherStore = useOtherStore()
return state.count + otherStore.count
}
}
})
將參數傳遞給 getter
getter 本質上是一個 computed ,無法向它傳遞任何參數。但是,我們可以讓它返回一個函數以接受參數:
// src/stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () ({
users: [{ id: 1, name: 'Tom'}, {id: 2, name: 'Jack'}]
}),
getters: {
getUserById: (state) => {
return (userId) => state.users.find((user) => user.id === userId)
}
}
})
在組件中使用:
<script setup>
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const { getUserById } = storeToRefs(userStore)
</script>
<template>
<p>User: {{ getUserById(2) }}</p>
</template>
注意:如果這樣使用,getter 不會緩存,它只會當作一個普通函數使用。一般不推薦這種用法,因為在組件中定義一個函數,可以實現同樣的功能。
Actions
訪問 store 實例
與 getters 一樣,actions 可以通過 this 訪問當 store 的實例。不同的是,actions 可以是異步的。
// src/stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () ({ userData: null }),
actions: {
async registerUser(login, password) {
try {
this.userData = await api.post({ login, password })
} catch (error) {
return error
}
}
}
})
訪問其他 Store 的 action
要使用其他 Store 的 action,也可以直接在 action 內部使用:
// src/stores/setting.js
import { defineStore } from 'pinia'
import { useAuthStore } from './authStore'
export const useSettingStore = defineStore('setting', {
state: () ({ preferences: null }),
actions: {
async fetchUserPreferences(preferences) {
const authStore = useAuthStore()
if (authStore.isAuthenticated()) {
this.preferences = await fetchPreferences()
} else {
throw new Error('User must be authenticated!')
}
}
}
})
以上就是 Pinia 的詳細用法,是不是比 Vuex 簡單多了。除此之外,插件也是 Pinia 的一個亮點,個人覺得非常實用,下面我們就來重點介紹一下。
Plugins
由于是底層 API,Pania Store 完全支持擴展。以下是可以擴展的功能列表: - 向 Store 添加新狀態 - 定義 Store 時添加新選項 - 為 Store 添加新方法 - 包裝現有方法 - 更改甚至取消操作 - 實現本地存儲等副作用 - 僅適用于特定 Store
使用方法
Pinia 插件是一個函數,接受一個可選參數 context ,context 包含四個屬性:app 實例、pinia 實例、當前 store 和選項對象。函數也可以返回一個對象,對象的屬性和方法會分別添加到 state 和 actions 中。
export function myPiniaPlugin(context) {
context.app // 使用 createApp() 創建的 app 實例(僅限 Vue 3)
context.pinia // 使用 createPinia() 創建的 pinia
context.store // 插件正在擴展的 store
context.options // 傳入 defineStore() 的選項對象(第二個參數)
// ...
return {
hello: 'world', // 為 state 添加一個 hello 狀態
changeHello() { // 為 actions 添加一個 changeHello 方法
this.hello = 'pinia'
}
}
}
然后使用 pinia.use() 將此函數傳遞給 pinia 就可以了:
// src/main.js
import { createPinia } from 'pinia'
const pinia = createPinia()
pinia.use(myPiniaPlugin)
向 Store 添加新狀態
可以簡單地通過返回一個對象來為每個 store 添加狀態:
pinia.use(() ({ hello: 'world' }))
也可以直接在 store 上設置屬性來添加狀態,為了使它可以在 devtools 中使用,還需要對 store.$state 進行設置:
import { ref, toRef } from 'vue'
pinia.use(({ store }) {
const hello = ref('word')
store.$state.hello = hello
store.hello = toRef(store.$state, 'hello')
})
也可以在 use 方法外面定義一個狀態,共享全局的 ref 或 computed :
import { ref } from 'vue'
const globalSecret = ref('secret')
pinia.use(({ store }) => {
// `secret` 在所有 store 之間共享
store.$state.secret = globalSecret
store.secret = globalSecret
})
定義 Store 時添加新選項
可以在定義 store 時添加新的選項,以便在插件中使用它們。例如,可以添加一個 debounce 選項,允許對所有操作進行去抖動:
// src/stores/search.js
import { defineStore } from 'pinia'
export const useSearchStore = defineStore('search', {
actions: {
searchContacts() {
// ...
},
searchContent() {
// ...
}
},
debounce: {
// 操作 searchContacts 防抖 300ms
searchContacts: 300,
// 操作 searchContent 防抖 500ms
searchContent: 500
}
})
然后使用插件讀取該選項,包裝并替換原始操作:
// src/main.js
import { createPinia } from 'pinia'
import { debounce } from 'lodash'
const pinia = createPinia()
pinia.use(({ options, store }) => {
if (options.debounce) {
// 我們正在用新的 action 覆蓋原有的 action
return Object.keys(options.debounce).reduce((debouncedActions, action) => {
debouncedActions[action] = debounce(
store[action],
options.debounce[action]
)
return debouncedActions
}, {})
}
})
這樣在組件中使用 actions 的方法就可以去抖動了,是不是很方便!
實現本地存儲
相信大家使用 Vuex 都有這樣的困惑,F5 刷新一下數據全沒了。在我們眼里這很正常,但在測試同學眼里這就是一個 bug 。Vuex 中實現本地存儲比較麻煩,需要把狀態一個一個存儲到本地,取數據時也要進行處理。而使用 Pinia ,一個插件就可以搞定。
這次我們就不自己寫了,直接安裝開源插件。
npm i pinia-plugin-persist
然后引入插件,并將此插件傳遞給 pinia :
// src/main.js
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPluginPersist)
接著在定義 store 時開啟 persist 即可:
// src/stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () ({ count: 1 }),
// 開啟數據緩存
persist: {
enabled: true
}
})
這樣,無論你用什么姿勢刷新,數據都不會丟失啦!
默認情況下,會以 storeId 作為 key 值,把 state 中的所有狀態存儲在 sessionStorage 中。我們也可以通過 strategies 進行修改:
// 開啟數據緩存
persist: {
enabled: true,
strategies: [
{
key: 'myCounter', // 存儲的 key 值,默認為 storeId
storage: localStorage, // 存儲的位置,默認為 sessionStorage
paths: ['name', 'age'], // 需要存儲的 state 狀態,默認存儲所有的狀態
}
]
}
ok,今天的分享就是這些。不知道你對 Pinia 是不是有了更進一步的了解,歡迎評論區留言討論。
小結
Pinia 整體來說比 Vuex 更加簡單、輕量,但功能卻更加強大,也許這就是它取代 Vuex 的原因吧。此外,Pinia 還可以在 Vue2 中結合 map 函數使用,有興趣的同學可以研究一下。