一文詳解Pinia和Vuex與兩個Vue狀態(tài)管理模式
前言
Pinia和Vuex一樣都是是vue的全局狀態(tài)管理器。其實Pinia就是Vuex5,只不過為了尊重原作者的貢獻就沿用了這個看起來很甜的名字Pinia。
本文將通過Vue3的形式對兩者的不同實現(xiàn)方式進行對比,讓你在以后工作中無論使用到Pinia還是Vuex的時候都能夠游刃有余。
既然我們要對比兩者的實現(xiàn)方式,那么我們肯定要先在我們的Vue3項目中引入這兩個狀態(tài)管理器(實際項目中千萬不要即用Vuex又用Pinia,不然你會被同事請去喝茶的。下面就讓我們看下它們的使用方式吧
安裝
Vuex
npm i vuex -S
Pinia
npm i pinia -S
掛載
Vuex
在src目錄下新建vuexStore,實際項目中你只需要建一個store目錄即可,由于我們需要兩種狀態(tài)管理器,所以需要將其分開并創(chuàng)建兩個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中的計算屬性 getters: { }, //將store分割成模塊(module),應用較大時使用 modules: { } })
main.js引入
import { createApp } from 'vue' import App from './App.vue' import store from '@/vuexStore' createApp(App).use(store).mount('#app')
App.vue測試
<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引入)的方式引入模塊,因為它的每個store便是一個模塊,如storeA,storeB... 。 在我們使用Vuex的時候每次修改state的值都需要調(diào)用mutations里的修改函數(shù)(下面會說到),因為Vuex需要追蹤數(shù)據(jù)的變化,這使我們寫起來比較繁瑣。而pinia則不再需要mutations,同步異步都可在actions進行操作,至于它沒有了mutations具體是如何最終到state變化的,這里我們不過多深究,大概好像應該是通過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的而且還是響應式的,但是如果這樣做了,vuex不能夠記錄每一次state的變化記錄,影響我們的調(diào)試。當vuex開啟嚴格模式的時候,直接修改state會拋出錯誤,所以官方建議我們開啟嚴格模式,所有的state變更都在vuex內(nèi)部進行,在mutations進行修改。例如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中的計算屬性 getters: {}, //將store分割成模塊(module),應用較大時使用 modules: {}, });
當我們需要修改vuexmsg的時候需要提交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中進行提交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è)這里進行了請求并拿到了返回值 commit("setVuexMsg", "hello juejin"); }, } });
組件中使用dispatch進行分發(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ù),拿請求后端接口為例,當后端接口返回值的時候,actions中會提交一個mutations中的函數(shù),然后這個函數(shù)對vuex中的狀態(tài)(state)進行一個修改,組件中再渲染這個狀態(tài),從而實現(xiàn)整個數(shù)據(jù)流程都在vuex內(nèi)部進行便于檢測。直接看圖,一目了然
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方法可以修改多個state中的值,比如我們在piniaStore/storeA.js中的state增加一個name
import { defineStore } from "pinia"; export const storeA = defineStore("storeA", { state: () => { return { piniaMsg: "hello pinia", name: "xiaoyue", }; }, getters: {}, actions: {}, });
然后我們在App.vue中進行修改這兩個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
當然也是支持修改單個狀態(tài)的如
piniaStoreA.$patch({ name: 'daming' })
$patch還可以使用函數(shù)的方式進行修改狀態(tài)
import { storeA } from '@/piniaStore/storeA' let piniaStoreA = storeA() cartStore.$patch((state) => { state.name = 'daming' state.piniaMsg = 'hello juejin' })
- 在actions中進行修改
不同于Vuex的是,Pinia去掉了mutations,所以在actions中修改state就行Vuex在mutations修改state一樣。其實這也是我比較推薦的一種修改狀態(tài)的方式,就像上面說的,這樣可以實現(xiàn)整個數(shù)據(jù)流程都在狀態(tài)管理器內(nèi)部,便于管理。
在piniaStore/storeA.js的actions添加一個修改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)
當我們組件中需要用到state中多個參數(shù)時,使用解構(gòu)的方式取值往往是很方便的,但是傳統(tǒng)的ES6解構(gòu)會使state失去響應式,比如組件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
為了解決這個問題,Pinia提供了一個結(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
其實Vuex中的getters和Pinia中的getters用法是一致的,用于自動監(jiān)聽對應state的變化,從而動態(tài)計算返回值(和vue中的計算屬性差不多),并且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>
讓我們來看下什么是緩存特性。首先我們在組件多次訪問sum再看下控制臺打印
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é)果我們可以看出只有在首次使用用或者當我們改變sum所依賴的值的時候,getters中的sum才會被調(diào)用
Vuex
Vuex中的getters使用和Pinia的使用方式類似,就不再進行過多說明,寫法如下vuexStore/index.js
import { createStore } from "vuex"; export default createStore({ strict: true, //全局state,類似于vue種的data state: { count1: 1, count2: 2, }, //類似于vue中的計算屬性 getters: { sum(state){ return state.count1 + state.count2 } } });
modules
如果項目比較大,使用單一狀態(tài)庫,項目的狀態(tài)庫就會集中到一個大對象上,顯得十分臃腫難以維護。所以Vuex就允許我們將其分割成模塊(modules),每個模塊都擁有自己state,mutations,actions...。而Pinia每個狀態(tài)庫本身就是一個模塊。
Pinia
Pinia沒有modules,如果想使用多個store,直接定義多個store傳入不同的id即可,如:
import { defineStore } from "pinia"; export const storeA = defineStore("storeA", {...}); export const storeB = defineStore("storeB", {...}); export const storeC = defineStore("storeB", {...});
Vuex
一般來說每個module都會新建一個文件,然后再引入這個總的入口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一般會采用命名空間的方式 namespaced: true 如moduleA:
const moduleA = { namespaced: true, state: () => ({ count: 1, }), mutations: { setCount(state, data) { state.count = data; }, }, actions: { getuser() { //do something }, }, }
此時如果我們再調(diào)用setCount或者getuser
vuexStore.commit('moduleA/setCount', 2) vuexStore.dispatch('moduleA/getuser')
寫在最后
通過以上案例我們會發(fā)現(xiàn)Pinia比Vuex簡潔許多,所以如果我們的項目是新項目的話建議使用Pinia。 當然如果我們的項目體量不是很大,我們其實沒必要引入vue的狀態(tài)管理庫,盲目的使用反而會徒增心智負擔。
到此這篇關(guān)于一文詳解Pinia和Vuex與兩個Vue狀態(tài)管理模式的文章就介紹到這了,更多相關(guān)Vue狀態(tài)管理模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue父組件調(diào)用子組件函數(shù)實現(xiàn)
這篇文章主要介紹了Vue父組件調(diào)用子組件函數(shù)實現(xiàn),全文通過舉例子及代碼的形式進行了一個簡單的介紹,希望大家能夠理解并且學習到其中知識2021-08-08vue3使用vuex實現(xiàn)頁面實時更新數(shù)據(jù)實例教程(setup)
在前端開發(fā)中往往會遇到頁面需要實時刷新數(shù)據(jù)的情況,給用戶最新的數(shù)據(jù)展示,這篇文章主要給大家介紹了關(guān)于vue3使用vuex實現(xiàn)頁面實時更新數(shù)據(jù)(setup)的相關(guān)資料,需要的朋友可以參考下2022-09-09簡單實現(xiàn)Vue的observer和watcher
這篇文章主要教大家如何簡單實現(xiàn)Vue的observer和watcher,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12Vue?export?default中的name屬性有哪些作用
這篇文章主要介紹了Vue?export?default中的name屬性有哪些作用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03ElementUI日期選擇器時間選擇范圍限制的實現(xiàn)
在日常開發(fā)中,我們會遇到一些情況,限制日期的范圍的選擇,本文就詳細的介紹了ElementUI日期選擇器時間選擇范圍限制的實現(xiàn),文中通過示例代碼介紹的非常詳細,感興趣的可以了解一下2022-04-04vue+echarts實現(xiàn)可拖動節(jié)點的折線圖(支持拖動方向和上下限的設(shè)置)
制作一個折線圖用于顯示當前24小時的數(shù)據(jù),并且可以通過拖動折現(xiàn)圖設(shè)置數(shù)據(jù),接下來通過本文給大家分享vue+echarts實現(xiàn)可拖動節(jié)點的折線圖(支持拖動方向和上下限的設(shè)置),感興趣的朋友跟隨一起學習吧2019-04-04