Pinia和Vuex一樣都是是vue的全局狀態(tài)管理器。其實(shí)Pinia就是Vuex5,只不過為了尊重原作者的貢獻(xiàn)就沿用了這個(gè)看起來很甜的名字Pinia。
本文將通過Vue3的形式對(duì)兩者的不同實(shí)現(xiàn)方式進(jìn)行對(duì)比,讓你在以后工作中無論使用到Pinia還是Vuex的時(shí)候都能夠游刃有余。
既然我們要對(duì)比兩者的實(shí)現(xiàn)方式,那么我們肯定要先在我們的Vue3項(xiàng)目中引入這兩個(gè)狀態(tài)管理器(實(shí)際項(xiàng)目中千萬不要即用Vuex又用Pinia,不然你會(huì)被同事請(qǐng)去喝茶的。下面就讓我們看下它們的使用方式吧
安裝
-
Vuex
-
Pinia
掛載Vuex
在src目錄下新建vuexStore,實(shí)際項(xiàng)目中你只需要建一個(gè)store目錄即可,由于我們需要兩種狀態(tài)管理器,所以需要將其分開并創(chuàng)建兩個(gè)store目錄
新建vuexStore/index.js
import{ createStore } from'vuex'
exportdefaultcreateStore({
//全局state,類似于vue種的data
state {
return{
vuexmsg: "hello vuex",
name: "xiaoyue",
};
},
//修改state函數(shù)
mutations: {
},
//提交的mutation可以包含任意異步操作
actions: {
},
//類似于vue中的計(jì)算屬性
getters: {
},
//將store分割成模塊(module),應(yīng)用較大時(shí)使用
modules: {
}
})
main.js引入
import{ createApp } from'vue'
importApp from'./App.vue'
importstore from'@/vuexStore'
createApp(App).use(store).mount( '#app')
App.vue測(cè)試
< template>
< div> </ div>
</ template>
< setup>
import{ useStore } from'vuex'
letvuexStore = useStore
console.log(vuexStore.state.vuexmsg); //hello vuex
</ >
頁面正常打印hello vuex說明我們的Vuex已經(jīng)掛載成功了
Pinia
-
main.js引入
importApp from"./App.vue";
import{createPinia} from'pinia'
constpinia = createPinia
createApp(App).use(pinia).mount( "#app");
-
創(chuàng)建Store
src下新建piniaStore/storeA.js
import{ defineStore } from"pinia";
exportconststoreA = defineStore( "storeA", {
state: => {
return{
piniaMsg: "hello pinia",
};
},
getters: {},
actions: {},
});
-
App.vue使用
< div> </ div>
</ template>
< setup>
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
console.log(piniaStoreA.piniaMsg); //hello pinia
</ >
從這里我們可以看出pinia中沒有了mutations和modules,pinia不必以嵌套(通過modules引入)的方式引入模塊,因?yàn)樗拿總€(gè)store便是一個(gè)模塊,如storeA,storeB... 。
在我們使用Vuex的時(shí)候每次修改state的值都需要調(diào)用mutations里的修改函數(shù)(下面會(huì)說到),因?yàn)閂uex需要追蹤數(shù)據(jù)的變化,這使我們寫起來比較繁瑣。而pinia則不再需要mutations,同步異步都可在actions進(jìn)行操作,至于它沒有了mutations具體是如何最終到state變化的,這里我們不過多深究, 大概好像應(yīng)該是通過hooks回調(diào)的形式解決的把(我也沒研究過,瞎猜的。
修改狀態(tài)
獲取state的值從上面我們已經(jīng)可以一目了然的看到了,下面讓我們看看他倆修改state的方法吧
vuex
vuex在組件中直接修改state,如App.vue
< template>
< div> {{vuexStore.state.vuexmsg}} </ div>
</ template>
< setup>
import{ useStore } from'vuex'
letvuexStore = useStore
vuexStore.state.vuexmsg = 'hello juejin'
console.log(vuexStore.state.vuexmsg)
</ >
可以看出我們是可以直接在組件中修改state的而且還是響應(yīng)式的,但是如果這樣做了,vuex不能夠記錄每一次state的變化記錄,影響我們的調(diào)試。
當(dāng)vuex開啟嚴(yán)格模式的時(shí)候,直接修改state會(huì)拋出錯(cuò)誤,所以官方建議我們開啟嚴(yán)格模式,所有的state變更都在vuex內(nèi)部進(jìn)行,在mutations進(jìn)行修改。例如vuexStore/index.js:
import{ createStore } from"vuex";
exportdefaultcreateStore({
strict: true,
//全局state,類似于vue種的data
state: {
vuexmsg: "hello vuex",
},
//修改state函數(shù)
mutations: {
setVuexMsg(state, data) {
state.vuexmsg = data;
},
},
//提交的mutation可以包含任意異步操作
actions: {},
//類似于vue中的計(jì)算屬性
getters: {},
//將store分割成模塊(module),應(yīng)用較大時(shí)使用
modules: {},
});
當(dāng)我們需要修改vuexmsg的時(shí)候需要提交setVuexMsg方法,如App.vue
< template>
< div> {{ vuexStore.state.vuexmsg }} </ div>
</ template>
< setup>
import{ useStore } from'vuex'
letvuexStore = useStore
vuexStore.commit( 'setVuexMsg', 'hello juejin')
console.log(vuexStore.state.vuexmsg) //hello juejin
</ >
或者我們可以在actions中進(jìn)行提交mutations修改state:
import{ createStore } from"vuex";
exportdefaultcreateStore({
strict: true,
//全局state,類似于vue種的data
state {
return{
vuexmsg: "hello vuex",
}
},
//修改state函數(shù)
mutations: {
setVuexMsg(state, data) {
state.vuexmsg = data;
},
},
//提交的mutation可以包含任意異步操作
actions: {
asyncgetState({ commit }) {
//const result = await xxxx 假設(shè)這里進(jìn)行了請(qǐng)求并拿到了返回值
commit( "setVuexMsg", "hello juejin");
},
}
});
組件中使用dispatch進(jìn)行分發(fā)actions
< template>
< div> {{ vuexStore.state.vuexmsg }} </ div>
</ template>
< setup>
import{ useStore } from'vuex'
letvuexStore = useStore
vuexStore.dispatch( 'getState')
</ >
一般來說,vuex中的流程是首先actions一般放異步函數(shù),拿請(qǐng)求后端接口為例,當(dāng)后端接口返回值的時(shí)候,actions中會(huì)提交一個(gè)mutations中的函數(shù),然后這個(gè)函數(shù)對(duì)vuex中的狀態(tài)(state)進(jìn)行一個(gè)修改,組件中再渲染這個(gè)狀態(tài),從而實(shí)現(xiàn)整個(gè)數(shù)據(jù)流程都在vuex內(nèi)部進(jìn)行便于檢測(cè)。直接看圖,一目了然
Pinia
-
直接修改
相比于Vuex,Pinia是可以直接修改狀態(tài)的,并且調(diào)試工具能夠記錄到每一次state的變化,如App.vue
< template>
< div> {{ piniaStoreA.piniaMsg }} </ div>
</ template>
< setup>
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
console.log(piniaStoreA.piniaMsg); //hello pinia
piniaStoreA.piniaMsg = 'hello juejin'
console.log(piniaStoreA.piniaMsg); //hello juejin
</ >
-
$patch
使用$patch方法可以修改多個(gè)state中的值,比如我們?cè)趐iniaStore/storeA.js中的state增加一個(gè)name
import{ defineStore } from"pinia";
exportconststoreA = defineStore( "storeA", {
state: => {
return{
piniaMsg: "hello pinia",
name: "xiaoyue",
};
},
getters: {},
actions: {},
});
然后我們?cè)贏pp.vue中進(jìn)行修改這兩個(gè)state
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
console.log(piniaStoreA.name); //xiaoyue
piniaStoreA.$patch({
piniaMsg: 'hello juejin',
name: 'daming'
})
console.log(piniaStoreA.name); //daming
當(dāng)然也是支持修改單個(gè)狀態(tài)的如
piniaStoreA. $patch({
name: 'daming'
})
$patch還可以使用函數(shù)的方式進(jìn)行修改狀態(tài)
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA
cartStore.$patch((state) => {
state.name = 'daming'
state.piniaMsg = 'hello juejin'
})
-
在actions中進(jìn)行修改
不同于Vuex的是,Pinia去掉了mutations,所以在actions中修改state就行Vuex在mutations修改state一樣。其實(shí)這也是我比較推薦的一種修改狀態(tài)的方式,就像上面說的,這樣可以實(shí)現(xiàn)整個(gè)數(shù)據(jù)流程都在狀態(tài)管理器內(nèi)部,便于管理。
在piniaStore/storeA.js的actions添加一個(gè)修改name的函數(shù)
import{ defineStore } from"pinia";
exportconststoreA = defineStore( "storeA", {
state: => {
return{
piniaMsg: "hello pinia",
name: "xiao yue",
};
},
actions: {
setName(data) {
this.name = data;
},
},
});
組件App.vue中調(diào)用不需要再使用dispatch函數(shù),直接調(diào)用store的方法即可
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
piniaStoreA.setName( 'daming')
-
重置state
Pinia可以使用$reset將狀態(tài)重置為初始值
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
piniaStoreA.$reset
Pinia解構(gòu)(storeToRefs)
當(dāng)我們組件中需要用到state中多個(gè)參數(shù)時(shí),使用解構(gòu)的方式取值往往是很方便的,但是傳統(tǒng)的ES6解構(gòu)會(huì)使state失去響應(yīng)式,比如組件App.vue,我們先解構(gòu)取得name值,然后再去改變name值,然后看頁面是否變化
< template>
< div> {{ name }} </ div>
</ template>
< setup>
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
let{ piniaMsg, name } = piniaStoreA
piniaStoreA.$patch({
name: 'daming'
})
</ >
瀏覽器展示如下
我們可以發(fā)現(xiàn)瀏覽器并沒有更新頁面為daming
為了解決這個(gè)問題,Pinia提供了一個(gè)結(jié)構(gòu)方法 storeToRefs,我們將組件App.vue使用 storeToRefs解構(gòu)
< template>
< div> {{ name }} </ div>
</ template>
< setup>
import{ storeA } from'@/piniaStore/storeA'
import{ storeToRefs } from'pinia'
letpiniaStoreA = storeA
let{ piniaMsg, name } = storeToRefs(piniaStoreA)
piniaStoreA.$patch({
name: 'daming'
})
</ >
再看下頁面變化
我們發(fā)現(xiàn)頁面已經(jīng)被更新成daming了
getters
其實(shí)Vuex中的getters和Pinia中的getters用法是一致的,用于自動(dòng)監(jiān)聽對(duì)應(yīng)state的變化,從而動(dòng)態(tài)計(jì)算返回值(和vue中的計(jì)算屬性差不多),并且getters的值也具有緩存特性
Pinia
我們先將piniaStore/storeA.js改為
import{ defineStore } from"pinia";
exportconststoreA = defineStore( "storeA", {
state: => {
return{
count1: 1,
count2: 2,
};
},
getters: {
sum {
console.log( '我被調(diào)用了!')
returnthis.count1 + this.count2;
},
},
});
然后在組件App.vue中獲取sum
< template>
< div> {{ piniaStoreA.sum }} </ div>
</ template>
< setup>
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
console.log(piniaStoreA.sum) //3
</ >
讓我們來看下什么是緩存特性。首先我們?cè)诮M件多次訪問sum再看下控制臺(tái)打印
import{ storeA } from'@/piniaStore/storeA'
letpiniaStoreA = storeA
console.log(piniaStoreA.sum)
console.log(piniaStoreA.sum)
console.log(piniaStoreA.sum)
piniaStoreA.count1 = 2
console.log(piniaStoreA.sum)
從打印結(jié)果我們可以看出只有在首次使用用或者當(dāng)我們改變sum所依賴的值的時(shí)候,getters中的sum才會(huì)被調(diào)用
Vuex
Vuex中的getters使用和Pinia的使用方式類似,就不再進(jìn)行過多說明,寫法如下vuexStore/index.js
import{ createStore } from"vuex";
exportdefaultcreateStore({
strict: true,
//全局state,類似于vue種的data
state: {
count1: 1,
count2: 2,
},
//類似于vue中的計(jì)算屬性
getters: {
sum(state){
returnstate.count1 + state.count2
}
}
});
modules
如果項(xiàng)目比較大,使用單一狀態(tài)庫,項(xiàng)目的狀態(tài)庫就會(huì)集中到一個(gè)大對(duì)象上,顯得十分臃腫難以維護(hù)。所以Vuex就允許我們將其分割成模塊(modules),每個(gè)模塊都擁有自己state,mutations,actions...。而Pinia每個(gè)狀態(tài)庫本身就是一個(gè)模塊。
Pinia
Pinia沒有modules,如果想使用多個(gè)store,直接定義多個(gè)store傳入不同的id即可,如:
import { defineStore } from "pinia";
export const storeA = defineStore("storeA", {...});
export const storeB = defineStore("storeB", {...});
export const storeC = defineStore("storeB", {...}); Vuex
一般來說每個(gè)module都會(huì)新建一個(gè)文件,然后再引入這個(gè)總的入口index.js中,這里為了方便就寫在了一起
import{ createStore } from"vuex";
constmoduleA = {
state: => ({
count: 1
}),
mutations: {
setCount(state, data) {
state.count = data;
},
},
actions: {
getuser {
//do something
},
},
getters: { ... }
}
constmoduleB = {
state: => ({ ... }),
mutations: { ... },
actions: { ... }
}
exportdefaultcreateStore({
strict: true,
//全局state,類似于vue種的data
state {
return{
vuexmsg: "hello vuex",
name: "xiaoyue",
};
},
modules: {
moduleA,
moduleB
},
});
使用moduleA
import{ useStore } from'vuex'
letvuexStore = useStore
console.log(vuexStore.state.moduleA.count) //1
vuexStore.commit( 'setCount', 2)
console.log(vuexStore.state.moduleA.count) //2
vuexStore.dispatch( 'getuser')
一般我們?yōu)榱朔乐固峤灰恍﹎utation或者actions中的方法重名,modules一般會(huì)采用命名空間的方式 namespaced: true如moduleA:
const moduleA = {
namespaced: true,
state: => ({
count: 1,
}),
mutations: {
setCount(state, data) {
state.count = data;
},
},
actions: {
getuser {
//do something
},
},
}
此時(shí)如果我們?cè)僬{(diào)用setCount或者getuser
vuexStore.commit('moduleA/setCount', 2)
vuexStore.dispatch('moduleA/getuser')
作者:東方小月