Pinia進(jìn)階setup函數(shù)式寫法封裝到企業(yè)項(xiàng)目
開場
Hello大家好,相信在座各位假如使用Vue生態(tài)開發(fā)項(xiàng)目情況下,對Pinia
狀態(tài)管理庫應(yīng)該有所聽聞或正在使用,假如還沒接觸到Pinia,這篇文章可以幫你快速入門,并如何在企業(yè)項(xiàng)目中更優(yōu)雅封裝使用。
本文先給大家闡述如何去理解、使用Pinia,最后講怎樣把Pinia集成到工程中,適合大多數(shù)讀者,至于研讀Pinia的源碼等進(jìn)階科普,會(huì)另外開一篇文章細(xì)述。另外,本文的所有demo,都專門開了個(gè)GitHub項(xiàng)目來保存,有需要的同學(xué)可以拿下來實(shí)操一下。????
認(rèn)識(shí)Pinia
Pinia
讀音:/pi?nj?/,是Vue官方團(tuán)隊(duì)推薦代替Vuex
的一款輕量級狀態(tài)管理庫。 它最初的設(shè)計(jì)理念是讓Vue Store擁有一款Composition API方式的狀態(tài)管理庫,并同時(shí)能支持 Vue2.x版本的Option API 和 Vue3版本的setup Composition API開發(fā)模式,并完整兼容Typescript寫法(這也是優(yōu)于Vuex的重要因素之一),適用于所有的vue項(xiàng)目。
比起Vuex,Pinia具備以下優(yōu)點(diǎn):
- 完整的 TypeScript 支持:與在 Vuex 中添加 TypeScript 相比,添加 TypeScript 更容易
- 極其輕巧(體積約 1KB)
- store 的 action 被調(diào)度為常規(guī)的函數(shù)調(diào)用,而不是使用 dispatch 方法或 MapAction 輔助函數(shù),這在 Vuex 中很常見
- 支持多個(gè)Store
- 支持 Vue devtools、SSR 和 webpack 代碼拆分
Pinia與Vuex代碼分割機(jī)制
上述的Pinia輕量有一部分體現(xiàn)在它的代碼分割機(jī)制中。
舉個(gè)例子:某項(xiàng)目有3個(gè)store「user、job、pay」,另外有2個(gè)路由頁面「首頁、個(gè)人中心頁」,首頁用到j(luò)ob store,個(gè)人中心頁用到了user store,分別用Pinia和Vuex對其狀態(tài)管理。
先看Vuex的代碼分割: 打包時(shí),vuex會(huì)把3個(gè)store合并打包,當(dāng)首頁用到Vuex時(shí),這個(gè)包會(huì)引入到首頁一起打包,最后輸出1個(gè)js chunk。這樣的問題是,其實(shí)首頁只需要其中1個(gè)store,但其他2個(gè)無關(guān)的store也被打包進(jìn)來,造成資源浪費(fèi)。
Pinia的代碼分割: 打包時(shí),Pinia會(huì)檢查引用依賴,當(dāng)首頁用到j(luò)ob store,打包只會(huì)把用到的store和頁面合并輸出1個(gè)js chunk,其他2個(gè)store不耦合在其中。Pinia能做到這點(diǎn),是因?yàn)樗脑O(shè)計(jì)就是store分離的,解決了項(xiàng)目的耦合問題。
Pinia的常規(guī)用法
事不宜遲,直接開始使用Pinia
「本文默認(rèn)使用Vue3的setup Composition API開發(fā)模式」。
假如你對Pinia使用熟悉,可以略過這part
1. 安裝
yarn add pinia # or with npm npm install pinia
2. 掛載全局實(shí)例
import { createPinia } from 'pinia' app.use(createPinia())
3. 創(chuàng)建第一個(gè)store
在src/store/counterForOptions.ts
創(chuàng)建你的store。定義store模式有2種:
使用options API模式定義,這種方式和vue2的組件模型形式類似,也是對vue2技術(shù)棧開發(fā)者較為友好的編程模式。
import { defineStore } from 'pinia'; // 使用options API模式定義 export const useCounterStoreForOption = defineStore('counterForOptions', { // 定義state state: () => { return { count1: 1 }; }, // 定義action actions: { increment() { this.count1++; } }, // 定義getters getters: { doubleCount(state) { return state.count1 * 2; } } });
使用setup模式定義,符合Vue3 setup的編程模式,讓結(jié)構(gòu)更加扁平化,個(gè)人推薦推薦使用這種方式。
import { ref } from 'vue'; import { defineStore } from 'pinia'; // 使用setup模式定義 export const useCounterStoreForSetup = defineStore('counterForSetup', () => { const count = ref<number>(1); function increment() { count.value++; } function doubleCount() { return count.value * 2; } return { count, increment, doubleCount }; });
上面2種定義方式效果都是一樣的,我們用defineStore
方法定義一個(gè)store,里面分別定義1個(gè)count
的state,1個(gè)increment
action 和1個(gè)doubleCount
的getters。其中state是要共享的全局狀態(tài),而action則是讓業(yè)務(wù)方調(diào)用來改變state的入口,getters是獲取state的計(jì)算結(jié)果。
之所以用第一種方式定義是還要額外寫getters
、action
關(guān)鍵字來區(qū)分,是因?yàn)樵趏ptions API模式下可以通過mapState()、mapActions()等方法獲取對應(yīng)項(xiàng);但第二種方式就可以直接獲取了(下面會(huì)細(xì)述)。
4. 業(yè)務(wù)組件對store的調(diào)用
在src/components/PiniaBasicSetup.vue
目錄下創(chuàng)建個(gè)組件。
<script setup lang="ts" name="component-PiniaBasicSetup"> import { storeToRefs } from 'pinia'; import { useCounterStoreForSetup } from '@/store/counterForSetup'; // setup composition API模式 const counterStoreForSetup = useCounterStoreForSetup(); const { count } = storeToRefs(counterStoreForSetup); const { increment, doubleCount } = counterStoreForSetup; </script> <template> <div class="box-styl"> <h2>Setup模式</h2> <p class="section-box"> Pinia的state: count = <b>{{ count }}</b> </p> <p class="section-box"> Pinia的getters: doubleCount() = <b>{{ doubleCount() }}</b> </p> <div class="section-box"> <p>Pinia的action: increment()</p> <button @click="increment">點(diǎn)我</button> </div> </div> </template> <style lang="less" scoped> .box-styl { margin: 10px; .section-box { margin: 20px auto; width: 300px; background-color: #d7ffed; border: 1px solid #000; } } </style>
- Pinia在setup模式下的調(diào)用機(jī)制是先install再調(diào)用。
- install這樣寫:
const counterStoreForSetup = useCounterStoreForSetup();
,其中useCounterStoreForSetup
就是你定義store的變量; - 調(diào)用就直接用
counterStoreForSetup.xxx
(xxx包括:state、getters、action)就好。 - 代碼中獲取state是用了解構(gòu)賦值,為了保持state的響應(yīng)式特性,需要用
storeToRefs
進(jìn)行包裹。
兼容Vue2的Options API調(diào)用方式
<script lang="ts"> import { mapState, mapActions } from 'pinia'; import { useCounterStoreForOption } from '@/store/counterForOptions'; // setup composition API模式 export default { name: 'component-PiniaBasicOptions', computed: { // 獲取state和getters ...mapState(useCounterStoreForOption, ['count', 'doubleCount']) }, methods: { // 獲取action ...mapActions(useCounterStoreForOption, { increment: 'increment', reset: 'reset' }) } }; </script> <template> <div class="box-styl"> <h2>Options模式</h2> <p class="section-box"> Pinia的state: count = <b>{{ this.count }}</b> </p> <p class="section-box"> Pinia的getters: doubleCount() = <b>{{ this.doubleCount }}</b> </p> <div class="section-box"> <p>Pinia的action: increment()</p> <button @click="this.increment">點(diǎn)我</button> </div> <div class="section-box"> <p>Pinia的action: reset()</p> <button @click="this.reset">點(diǎn)我</button> </div> </div> </template> <style lang="less" scoped> .box-styl { margin: 10px; .section-box { margin: 20px auto; width: 300px; background-color: #d7ffed; border: 1px solid #000; } } </style>
5. 良好的編程習(xí)慣
state的改變交給action去處理: 上面例子,counterStoreForSetup
有個(gè)pinia實(shí)例屬性叫$state
是可以直接改變state的值,但不建議怎么做。一是難維護(hù),在組件繁多情況下,一處隱蔽state更改,整個(gè)開發(fā)組幫你排查;二是破壞store封裝,難以移植到其他地方。所以,為了你的聲譽(yù)和安全著想,請停止游離之外的coding????。
用hook代替pinia實(shí)例屬性: install后的counterStoreForSetup
對象里面,帶有不少$
開頭的方法,其實(shí)這些方法大多數(shù)都能通過hook引入代替。
其他的想到再補(bǔ)充...
企業(yè)項(xiàng)目封裝攻略
1. 全局注冊機(jī)
重復(fù)打包問題
在上面的例子我們可以知道,使用store時(shí)要先把store的定義import進(jìn)來,再執(zhí)行定義函數(shù)使得實(shí)例化。但是,在項(xiàng)目逐漸龐大起來后,每個(gè)組件要使用時(shí)候都要實(shí)例化嗎?在文中開頭講過,pinia的代碼分割機(jī)制是把引用它的頁面合并打包,那像下面的例子就會(huì)有問題,user被多個(gè)頁面引用,最后user store被重復(fù)打包。
為了解決這個(gè)問題,我們可以引入 ”全局注冊“ 的概念。做法如下:
創(chuàng)建總?cè)肟?/h4>
在src/store
目錄下創(chuàng)建一個(gè)入口index.ts
,其中包含一個(gè)注冊函數(shù)registerStore()
,其作用是把整個(gè)項(xiàng)目的store都提前注冊好,最后把所有的store實(shí)例掛到appStore
透傳出去。這樣以后,只要我們在項(xiàng)目任何組件要使用pinia時(shí),只要import appStore進(jìn)來,取對應(yīng)的store實(shí)例就行。
// src/store/index.ts import { roleStore } from './roleStore'; import { useCounterStoreForSetup } from '@/store/counterForSetup'; import { useCounterStoreForOption } from '@/store/counterForOptions'; export interface IAppStore { roleStore: ReturnType<typeof roleStore>; useCounterStoreForSetup: ReturnType<typeof useCounterStoreForSetup>; useCounterStoreForOption: ReturnType<typeof useCounterStoreForOption>; } const appStore: IAppStore = {} as IAppStore; /** * 注冊app狀態(tài)庫 */ export const registerStore = () => { appStore.roleStore = roleStore(); appStore.useCounterStoreForSetup = useCounterStoreForSetup(); appStore.useCounterStoreForOption = useCounterStoreForOption(); }; export default appStore;
總線注冊
在src/main.ts
項(xiàng)目總線執(zhí)行注冊操作:
import { createApp } from 'vue'; import App from './App.vue'; import { createPinia } from 'pinia'; import { registerStore } from '@/store'; const app = createApp(App); app.use(createPinia()); // 注冊pinia狀態(tài)管理庫 registerStore(); app.mount('#app');
業(yè)務(wù)組件內(nèi)直接使用
// src/components/PiniaBasicSetup.vue <script setup lang="ts" name="component-PiniaBasicSetup"> import { storeToRefs } from 'pinia'; import appStore from '@/store'; // setup composition API模式 const { count } = storeToRefs(appStore.useCounterStoreForSetup); const { increment, doubleCount } = appStore.useCounterStoreForSetup; </script> <template> <div class="box-styl"> <h2>Setup模式</h2> <p class="section-box"> Pinia的state: count = <b>{{ count }}</b> </p> <p class="section-box"> Pinia的getters: doubleCount() = <b>{{ doubleCount() }}</b> </p> <div class="section-box"> <p>Pinia的action: increment()</p> <button @click="increment">點(diǎn)我</button> </div> </div> </template>
打包解耦
到這里還不行,為了讓appStore
實(shí)例與項(xiàng)目解耦,在構(gòu)建時(shí)要把appStore
抽取到公共chunk,在vite.config.ts
做如下配置
export default defineConfig(({ command }: ConfigEnv) => { return { // ...其他配置 build: { // ...其他配置 rollupOptions: { output: { manualChunks(id) { // 將pinia的全局庫實(shí)例打包進(jìn)vendor,避免和頁面一起打包造成資源重復(fù)引入 if (id.includes(path.resolve(__dirname, '/src/store/index.ts'))) { return 'vendor'; } } } } } }; });
經(jīng)過這樣封裝后,pinia狀態(tài)庫得到解耦,最終的項(xiàng)目結(jié)構(gòu)圖是這樣的:
2. Store組管理
場景分析
大家在項(xiàng)目中是否經(jīng)常遇到某個(gè)方法要更新多個(gè)store的情況呢?例如:你要做個(gè)游戲,有3種職業(yè)「戰(zhàn)士、法師、道士」,另外,玩家角色有3個(gè)store來控制「人物屬性、裝備、技能」,頁面有個(gè)”轉(zhuǎn)職“按鈕,可以轉(zhuǎn)其他職業(yè)。當(dāng)玩家改變職業(yè)時(shí),3個(gè)store的state都要改變,怎么做呢?
- 方法1:在業(yè)務(wù)組件創(chuàng)建個(gè)函數(shù),單點(diǎn)擊”轉(zhuǎn)職“時(shí),獲取3個(gè)store并且更新它們的值。
- 方法2:抽象一個(gè)新pinia store,store里有個(gè)”轉(zhuǎn)職“的action,當(dāng)玩家轉(zhuǎn)職時(shí),響應(yīng)這個(gè)action,在action更新3個(gè)store的值。
對比起來,無論從封裝還是業(yè)務(wù)解耦,明顯方法2更好。要做到這樣,這也得益于pinia的store獨(dú)立管理特性,我們只需要把抽象的store作為父store,「人物屬性、裝備、技能」3個(gè)store作為單元store,讓父store的action去管理自己的單元store。
組級Store創(chuàng)建
繼續(xù)上才藝,父store:src/store/roleStore/index.ts
import { defineStore } from 'pinia'; import { roleBasic } from './basic'; import { roleEquipment } from './equipment'; import { roleSkill } from './skill'; import { ROLE_INIT_INFO } from './constants'; type TProfession = 'warrior' | 'mage' | 'warlock'; // 角色組,匯聚「人物屬性、裝備、技能」3個(gè)store統(tǒng)一管理 export const roleStore = defineStore('roleStore', () => { // 注冊組內(nèi)store const basic = roleBasic(); const equipment = roleEquipment(); const skill = roleSkill(); // 轉(zhuǎn)職業(yè) function changeProfession(profession: TProfession) { basic.setItem(ROLE_INIT_INFO[profession].basic); equipment.setItem(ROLE_INIT_INFO[profession].equipment); skill.setItem(ROLE_INIT_INFO[profession].skill); } return { basic, equipment, skill, changeProfession }; });
單元Store
3個(gè)單元store:
業(yè)務(wù)組件調(diào)用
<script setup lang="ts" name="component-StoreGroup"> import appStore from '@/store'; </script> <template> <div class="box-styl"> <h2>Store組管理</h2> <div class="section-box"> <p> 當(dāng)前職業(yè): <b>{{ appStore.roleStore.basic.basic.profession }}</b> </p> <p> 名字: <b>{{ appStore.roleStore.basic.basic.name }}</b> </p> <p> 性別: <b>{{ appStore.roleStore.basic.basic.sex }}</b> </p> <p> 裝備: <b>{{ appStore.roleStore.equipment.equipment }}</b> </p> <p> 技能: <b>{{ appStore.roleStore.skill.skill }}</b> </p> <span>轉(zhuǎn)職:</span> <button @click="appStore.roleStore.changeProfession('warrior')"> 戰(zhàn)士 </button> <button @click="appStore.roleStore.changeProfession('mage')">法師</button> <button @click="appStore.roleStore.changeProfession('warlock')"> 道士 </button> </div> </div> </template> <style lang="less" scoped> .box-styl { margin: 10px; .section-box { margin: 20px auto; width: 300px; background-color: #d7ffed; border: 1px solid #000; } } </style>
效果
落幕
磨刀不誤砍柴工,對于一個(gè)項(xiàng)目來講,好的狀態(tài)管理方案在當(dāng)中發(fā)揮重要的作用,不僅能讓項(xiàng)目思路清晰,而且便于項(xiàng)目日后維護(hù)和迭代。
項(xiàng)目demo https://github.com/JohnnyZhangQiao/pinia-use
以上就是Pinia進(jìn)階setup函數(shù)式寫法封裝到企業(yè)項(xiàng)目的詳細(xì)內(nèi)容,更多關(guān)于Pinia setup函數(shù)式封裝的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
創(chuàng)建Vue項(xiàng)目以及引入Iview的方法示例
這篇文章主要介紹了創(chuàng)建Vue項(xiàng)目以及引入Iview的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12C#實(shí)現(xiàn)將一個(gè)字符轉(zhuǎn)換為整數(shù)
下面小編就為大家分享一篇C#實(shí)現(xiàn)將一個(gè)字符轉(zhuǎn)換為整數(shù),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12vue3使用element-plus搭建后臺(tái)管理系統(tǒng)之菜單管理功能
這篇文章主要介紹了vue3使用element-plus搭建后臺(tái)管理系統(tǒng)之菜單管理,使用element-plus el-tree組件快速開發(fā)樹形菜單結(jié)構(gòu),el-tree組件中filter-node-method事件便可以實(shí)現(xiàn)樹形菜單篩選過濾功能,需要的朋友可以參考下2022-04-04vue3+vite應(yīng)用中添加sass預(yù)處理器問題
這篇文章主要介紹了vue3+vite應(yīng)用中添加sass預(yù)處理器問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02完美解決vue 項(xiàng)目開發(fā)越久 node_modules包越大的問題
這篇文章主要介紹了vue 項(xiàng)目開發(fā)越久 node_modules包越大的問題及解決方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09electron-vue開發(fā)環(huán)境內(nèi)存泄漏問題匯總
這篇文章主要介紹了electron-vue開發(fā)環(huán)境內(nèi)存泄漏問題匯總,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10