一文詳解Pinia和Vuex與兩個(gè)Vue狀態(tài)管理模式
前言
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
npm i vuex -S
Pinia
npm i pinia -S
掛載
Vuex
在src目錄下新建vuexStore,實(shí)際項(xiàng)目中你只需要建一個(gè)store目錄即可,由于我們需要兩種狀態(tài)管理器,所以需要將其分開并創(chuàng)建兩個(gè)store目錄
新建vuexStore/index.js
import { createStore } from 'vuex'
export default createStore({
//全局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'
import App from './App.vue'
import store from '@/vuexStore'
createApp(App).use(store).mount('#app')App.vue測(cè)試
<template>
<div></div>
</template>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
console.log(vuexStore.state.vuexmsg); //hello vuex
</script>頁面正常打印hello vuex說明我們的Vuex已經(jīng)掛載成功了
Pinia
- main.js引入
import { createApp } from "vue";
import App from "./App.vue";
import {createPinia} from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount("#app");- 創(chuàng)建Store
src下新建piniaStore/storeA.js
import { defineStore } from "pinia";
export const storeA = defineStore("storeA", {
state: () => {
return {
piniaMsg: "hello pinia",
};
},
getters: {},
actions: {},
});- App.vue使用
<template>
<div></div>
</template>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.piniaMsg); //hello pinia
</script>從這里我們可以看出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>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
vuexStore.state.vuexmsg = 'hello juejin'
console.log(vuexStore.state.vuexmsg)
</script>可以看出我們是可以直接在組件中修改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";
export default createStore({
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>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
vuexStore.commit('setVuexMsg', 'hello juejin')
console.log(vuexStore.state.vuexmsg) //hello juejin
</script>或者我們可以在actions中進(jìn)行提交mutations修改state:
import { createStore } from "vuex";
export default createStore({
strict: true,
//全局state,類似于vue種的data
state() {
return {
vuexmsg: "hello vuex",
}
},
//修改state函數(shù)
mutations: {
setVuexMsg(state, data) {
state.vuexmsg = data;
},
},
//提交的mutation可以包含任意異步操作
actions: {
async getState({ 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>
<script setup>
import { useStore } from 'vuex'
let vuexStore = useStore()
vuexStore.dispatch('getState')
</script>一般來說,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>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.piniaMsg); //hello pinia
piniaStoreA.piniaMsg = 'hello juejin'
console.log(piniaStoreA.piniaMsg); //hello juejin
</script>- $patch
使用$patch方法可以修改多個(gè)state中的值,比如我們?cè)趐iniaStore/storeA.js中的state增加一個(gè)name
import { defineStore } from "pinia";
export const storeA = defineStore("storeA", {
state: () => {
return {
piniaMsg: "hello pinia",
name: "xiaoyue",
};
},
getters: {},
actions: {},
});然后我們?cè)贏pp.vue中進(jìn)行修改這兩個(gè)state
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = 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";
export const storeA = 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'
let piniaStoreA = storeA()
piniaStoreA.setName('daming')- 重置state
Pinia可以使用$reset將狀態(tài)重置為初始值
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = 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>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
let { piniaMsg, name } = piniaStoreA
piniaStoreA.$patch({
name: 'daming'
})
</script>瀏覽器展示如下

我們可以發(fā)現(xiàn)瀏覽器并沒有更新頁面為daming
為了解決這個(gè)問題,Pinia提供了一個(gè)結(jié)構(gòu)方法storeToRefs,我們將組件App.vue使用storeToRefs解構(gòu)
<template>
<div>{{ name }}</div>
</template>
<script setup>
import { storeA } from '@/piniaStore/storeA'
import { storeToRefs } from 'pinia'
let piniaStoreA = storeA()
let { piniaMsg, name } = storeToRefs(piniaStoreA)
piniaStoreA.$patch({
name: 'daming'
})
</script>再看下頁面變化

我們發(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";
export const storeA = defineStore("storeA", {
state: () => {
return {
count1: 1,
count2: 2,
};
},
getters: {
sum() {
console.log('我被調(diào)用了!')
return this.count1 + this.count2;
},
},
});然后在組件App.vue中獲取sum
<template>
<div>{{ piniaStoreA.sum }}</div>
</template>
<script setup>
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = storeA()
console.log(piniaStoreA.sum) //3
</script>讓我們來看下什么是緩存特性。首先我們?cè)诮M件多次訪問sum再看下控制臺(tái)打印
import { storeA } from '@/piniaStore/storeA'
let piniaStoreA = 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";
export default createStore({
strict: true,
//全局state,類似于vue種的data
state: {
count1: 1,
count2: 2,
},
//類似于vue中的計(jì)算屬性
getters: {
sum(state){
return state.count1 + state.count2
}
}
});modules
如果項(xiàng)目比較大,使用單一狀態(tài)庫(kù),項(xiàng)目的狀態(tài)庫(kù)就會(huì)集中到一個(gè)大對(duì)象上,顯得十分臃腫難以維護(hù)。所以Vuex就允許我們將其分割成模塊(modules),每個(gè)模塊都擁有自己state,mutations,actions...。而Pinia每個(gè)狀態(tài)庫(kù)本身就是一個(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";
const moduleA = {
state: () => ({
count:1
}),
mutations: {
setCount(state, data) {
state.count = data;
},
},
actions: {
getuser() {
//do something
},
},
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
export default createStore({
strict: true,
//全局state,類似于vue種的data
state() {
return {
vuexmsg: "hello vuex",
name: "xiaoyue",
};
},
modules: {
moduleA,
moduleB
},
});使用moduleA
import { useStore } from 'vuex'
let vuexStore = 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')寫在最后
通過以上案例我們會(huì)發(fā)現(xiàn)Pinia比Vuex簡(jiǎn)潔許多,所以如果我們的項(xiàng)目是新項(xiàng)目的話建議使用Pinia。 當(dāng)然如果我們的項(xiàng)目體量不是很大,我們其實(shí)沒必要引入vue的狀態(tài)管理庫(kù),盲目的使用反而會(huì)徒增心智負(fù)擔(dān)。
到此這篇關(guān)于一文詳解Pinia和Vuex與兩個(gè)Vue狀態(tài)管理模式的文章就介紹到這了,更多相關(guān)Vue狀態(tài)管理模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3動(dòng)態(tài)加載對(duì)話框的方法實(shí)例
對(duì)話框是很常用的組件,在很多地方都會(huì)用到,下面這篇文章主要給大家介紹了關(guān)于vue3動(dòng)態(tài)加載對(duì)話框的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03
Vue實(shí)現(xiàn)圖片輪播組件思路及實(shí)例解析
這篇文章主要介紹了Vue實(shí)現(xiàn)圖片輪播組件思路及實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
vue頁面監(jiān)聽是否置為后臺(tái)或可見狀態(tài)問題
這篇文章主要介紹了vue頁面監(jiān)聽是否置為后臺(tái)或可見狀態(tài)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10

