Pinia
定義一個(gè)Store
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {})
這個(gè) name,也稱為 id,是必要的,Pinia 使用它來(lái)將 store 連接到 devtools。
將返回的函數(shù)命名為 use… 是跨可組合項(xiàng)的約定,以使其符合你的使用習(xí)慣。
使用 store
import { useStore } from '@/stores/counter'
const storeObj = useStore()
console.log(storeObj.count)
一旦 store 被實(shí)例化,你就可以直接在 store 上訪問(wèn) state
、getters
和 actions
中定義的任何屬性
store
是一個(gè)用reactive
包裹的對(duì)象,這意味著不需要在getter 之后寫(xiě).value
,就像
setup
中的props
一樣,我們不能對(duì)其進(jìn)行解構(gòu)
為了從 Store 中提取屬性同時(shí)保持其響應(yīng)式,您需要使用storeToRefs()
import { useStore } from '@/stores/counter'
const { count } = useStore()
console.log(count)//失去響應(yīng)
#解決
import { storeToRefs } from 'pinia'
const { count } = storeToRefs(useStore())
console.log(count.value)
state
在 Pinia 中,狀態(tài)被定義為返回初始狀態(tài)的函數(shù)。
const useStore = defineStore('main', {
state: () => {
return {count: 0}
})
訪問(wèn)“state”
const storeObj = useStore()
store.count++
重置狀態(tài)
const storeObj = useStore()
storeObj.$reset()
改變狀態(tài)
可以之惡杰修改: store.count++
可以調(diào)用 $patch 方法
storeObj.$patch({
otherProp: 'main'//其他屬性
count: storeObj.count + 1
})
或
storeObj.$patch((state) => {
state.item.push({name: 'RenNing', age: 18})
state.count = ++state.count
})
$patch
方法也接受一個(gè)函數(shù)來(lái)批量修改集合內(nèi)部分對(duì)象的情況
替換state
store.$state = { counter: 666, name: 'Paimon' } //{ counter: 666, name: 'Paimon' }
store.$state = {}
只針對(duì)原定義好的屬性,未定義的數(shù)據(jù)雖然會(huì)添加上,但是不起作用
訂閱狀態(tài)
通過(guò) store 的 $subscribe()
方法查看狀態(tài)及其變化
與常規(guī)的 watch()
相比,使用 $subscribe()
的優(yōu)點(diǎn)是 subscriptions 只會(huì)在 patches 之后觸發(fā)一次
storeObj.$subscribe((mutation, state) => {
// import { MutationType } from 'pinia'
mutation.type // 'direct' | 'patch object' | 'patch function'
// 與 cartStore.$id 相同
mutation.storeId // 'cart'
// 僅適用于 mutation.type === 'patch object'
mutation.payload // 補(bǔ)丁對(duì)象傳遞給 to cartStore.$patch()
// 每當(dāng)它發(fā)生變化時(shí),將整個(gè)狀態(tài)持久化到本地存儲(chǔ)
localStorage.setItem('cart', JSON.stringify(state))
})
認(rèn)情況下,state subscriptions 綁定到添加它們的組件
當(dāng)組件被卸載時(shí),它們將被自動(dòng)刪除
如果要在卸載組件后保留它們,請(qǐng)將 { detached: true }
作為第二個(gè)參數(shù)傳遞給 detach 當(dāng)前組件的 state subscription
storeObj.$subscribe(callback, {detached: true})
您可以在
pinia
實(shí)例上查看整個(gè)狀態(tài):watch( pinia.state, (state) => { // 每當(dāng)它發(fā)生變化時(shí),將整個(gè)狀態(tài)持久化到本地存儲(chǔ) localStorage.setItem('piniaState', JSON.stringify(state)) }, { deep: true } )
getter
用 defineStore()
中的 getters
屬性定義。
接收“狀態(tài)”作為第一個(gè)參數(shù)以鼓勵(lì)箭頭函數(shù)的使用
export const useStore = defineStore('count', {
state: () =>{{count: 1}},
getters: {
//方法一
doubleCount: (state) => {return state.count * 2},
//方法二
doublePlusOne(): number { return this.counter * 2 + 1 },
}
})
將參數(shù)傳遞給 getter
# 定義
getters: {
getUserId(state) =>{
const arr = state.foo.filter(....)
return (userId) => arr.find(id => userId == id)
}
}
#使用
{{getUserId(2)}}
執(zhí)行此操作時(shí),getter 不再緩存,它們只是您調(diào)用的函數(shù)。
但是,您可以在 getter 本身內(nèi)部緩存一些結(jié)果
反問(wèn)其他Store的getter
import {useOtherStore} from './other-sotre'
getters: {
otherGetter(state) {
const otherStore = useOtherStore()
return state.localDate + otherStore.data
}
}
沒(méi)有setup()
import { mapState } from 'pinia'
computed:{
...mapState(useCounterStroe, ['doubleCount'])
}
Actions
相當(dāng)于組件中的methods。適合定義業(yè)務(wù)邏輯
export const useStore = defineStore('main', {
actions: {
increment() {this.count++},
async getApi() {
try{
let res = await post('url',options)
}catch{
}
}
},
})
與 getters 一樣,操作可以通過(guò) this
訪問(wèn)
actions
可以是異步的
調(diào)用
Actions 像 methods 一樣被調(diào)用:
useStore.getApi()
不適用 setup()
可以使用 mapActions()
將操作屬性映射為組件中的方法
import { mapActions } from 'pinia'
import { getApi } from '../stores/useStore.js'
methods:{
...mapActions(getApi)
}
訂閱Actions
使用 store.$onAction()
訂閱 action 及其結(jié)果
const unsubscribe = someStore.$onAction(
({
name, // action 的名字
store, // store 實(shí)例
args, // 調(diào)用這個(gè) action 的參數(shù)
after, // 在這個(gè) action 執(zhí)行完畢之后,執(zhí)行這個(gè)函數(shù)
onError, // 在這個(gè) action 拋出異常的時(shí)候,執(zhí)行這個(gè)函數(shù)
}) => {
// 記錄開(kāi)始的時(shí)間變量
const startTime = Date.now()
// 這將在 `store` 上的操作執(zhí)行之前觸發(fā)
console.log(`Start "${name}" with params [${args.join(', ')}].`)
// 如果 action 成功并且完全運(yùn)行后,after 將觸發(fā)。
// 它將等待任何返回的 promise
after((result) => {
console.log(
`Finished "${name}" after ${
Date.now() - startTime
}ms.\nResult: ${result}.`
)
})
// 如果 action 拋出或返回 Promise.reject ,onError 將觸發(fā)
onError((error) => {
console.warn(
`Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
)
})
}
)
// 手動(dòng)移除訂閱
unsubscribe()
調(diào)用方法時(shí)/后觸發(fā)
默認(rèn)情況下,action subscriptions 綁定到添加它們的組件,默認(rèn)情況下,action subscriptions 綁定到添加它們的組件。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-632036.html
如果要在卸載組件后保留它們,請(qǐng)將 true
作為第二個(gè)參數(shù)傳遞給當(dāng)前組件的 detach action subscription文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-632036.html
// 此訂閱將在組件卸載后保留
someStore.$onAction(callback, true)
到了這里,關(guān)于vue3學(xué)習(xí)-Pinia狀態(tài)管理的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!