Pinia進階setup函數(shù)式寫法封裝到企業(yè)項目
開場
Hello大家好,相信在座各位假如使用Vue生態(tài)開發(fā)項目情況下,對Pinia狀態(tài)管理庫應(yīng)該有所聽聞或正在使用,假如還沒接觸到Pinia,這篇文章可以幫你快速入門,并如何在企業(yè)項目中更優(yōu)雅封裝使用。
本文先給大家闡述如何去理解、使用Pinia,最后講怎樣把Pinia集成到工程中,適合大多數(shù)讀者,至于研讀Pinia的源碼等進階科普,會另外開一篇文章細述。另外,本文的所有demo,都專門開了個GitHub項目來保存,有需要的同學(xué)可以拿下來實操一下。????
認識Pinia
Pinia讀音:/pi?nj?/,是Vue官方團隊推薦代替Vuex的一款輕量級狀態(tài)管理庫。 它最初的設(shè)計理念是讓Vue Store擁有一款Composition API方式的狀態(tài)管理庫,并同時能支持 Vue2.x版本的Option API 和 Vue3版本的setup Composition API開發(fā)模式,并完整兼容Typescript寫法(這也是優(yōu)于Vuex的重要因素之一),適用于所有的vue項目。
比起Vuex,Pinia具備以下優(yōu)點:
- 完整的 TypeScript 支持:與在 Vuex 中添加 TypeScript 相比,添加 TypeScript 更容易
- 極其輕巧(體積約 1KB)
- store 的 action 被調(diào)度為常規(guī)的函數(shù)調(diào)用,而不是使用 dispatch 方法或 MapAction 輔助函數(shù),這在 Vuex 中很常見
- 支持多個Store
- 支持 Vue devtools、SSR 和 webpack 代碼拆分
Pinia與Vuex代碼分割機制
上述的Pinia輕量有一部分體現(xiàn)在它的代碼分割機制中。
舉個例子:某項目有3個store「user、job、pay」,另外有2個路由頁面「首頁、個人中心頁」,首頁用到j(luò)ob store,個人中心頁用到了user store,分別用Pinia和Vuex對其狀態(tài)管理。

先看Vuex的代碼分割: 打包時,vuex會把3個store合并打包,當(dāng)首頁用到Vuex時,這個包會引入到首頁一起打包,最后輸出1個js chunk。這樣的問題是,其實首頁只需要其中1個store,但其他2個無關(guān)的store也被打包進來,造成資源浪費。

Pinia的代碼分割: 打包時,Pinia會檢查引用依賴,當(dāng)首頁用到j(luò)ob store,打包只會把用到的store和頁面合并輸出1個js chunk,其他2個store不耦合在其中。Pinia能做到這點,是因為它的設(shè)計就是store分離的,解決了項目的耦合問題。
Pinia的常規(guī)用法
事不宜遲,直接開始使用Pinia「本文默認使用Vue3的setup Composition API開發(fā)模式」。
假如你對Pinia使用熟悉,可以略過這part
1. 安裝
yarn add pinia # or with npm npm install pinia
2. 掛載全局實例
import { createPinia } from 'pinia'
app.use(createPinia())
3. 創(chuàng)建第一個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)更加扁平化,個人推薦推薦使用這種方式。
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方法定義一個store,里面分別定義1個count的state,1個increment action 和1個doubleCount的getters。其中state是要共享的全局狀態(tài),而action則是讓業(yè)務(wù)方調(diào)用來改變state的入口,getters是獲取state的計算結(jié)果。
之所以用第一種方式定義是還要額外寫getters、action關(guān)鍵字來區(qū)分,是因為在options API模式下可以通過mapState()、mapActions()等方法獲取對應(yīng)項;但第二種方式就可以直接獲取了(下面會細述)。
4. 業(yè)務(wù)組件對store的調(diào)用
在src/components/PiniaBasicSetup.vue目錄下創(chuàng)建個組件。
<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">點我</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)用機制是先install再調(diào)用。
- install這樣寫:
const counterStoreForSetup = useCounterStoreForSetup();,其中useCounterStoreForSetup就是你定義store的變量; - 調(diào)用就直接用
counterStoreForSetup.xxx(xxx包括:state、getters、action)就好。 - 代碼中獲取state是用了解構(gòu)賦值,為了保持state的響應(yīng)式特性,需要用
storeToRefs進行包裹。
兼容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">點我</button>
</div>
<div class="section-box">
<p>Pinia的action: reset()</p>
<button @click="this.reset">點我</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有個pinia實例屬性叫$state是可以直接改變state的值,但不建議怎么做。一是難維護,在組件繁多情況下,一處隱蔽state更改,整個開發(fā)組幫你排查;二是破壞store封裝,難以移植到其他地方。所以,為了你的聲譽和安全著想,請停止游離之外的coding????。
用hook代替pinia實例屬性: install后的counterStoreForSetup對象里面,帶有不少$開頭的方法,其實這些方法大多數(shù)都能通過hook引入代替。
其他的想到再補充...
企業(yè)項目封裝攻略
1. 全局注冊機
重復(fù)打包問題
在上面的例子我們可以知道,使用store時要先把store的定義import進來,再執(zhí)行定義函數(shù)使得實例化。但是,在項目逐漸龐大起來后,每個組件要使用時候都要實例化嗎?在文中開頭講過,pinia的代碼分割機制是把引用它的頁面合并打包,那像下面的例子就會有問題,user被多個頁面引用,最后user store被重復(fù)打包。

為了解決這個問題,我們可以引入 ”全局注冊“ 的概念。做法如下:
創(chuàng)建總?cè)肟?/h4>
在src/store目錄下創(chuàng)建一個入口index.ts,其中包含一個注冊函數(shù)registerStore(),其作用是把整個項目的store都提前注冊好,最后把所有的store實例掛到appStore透傳出去。這樣以后,只要我們在項目任何組件要使用pinia時,只要import appStore進來,取對應(yīng)的store實例就行。
// 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項目總線執(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">點我</button>
</div>
</div>
</template>
打包解耦
到這里還不行,為了讓appStore實例與項目解耦,在構(gòu)建時要把appStore抽取到公共chunk,在vite.config.ts做如下配置
export default defineConfig(({ command }: ConfigEnv) => {
return {
// ...其他配置
build: {
// ...其他配置
rollupOptions: {
output: {
manualChunks(id) {
// 將pinia的全局庫實例打包進vendor,避免和頁面一起打包造成資源重復(fù)引入
if (id.includes(path.resolve(__dirname, '/src/store/index.ts'))) {
return 'vendor';
}
}
}
}
}
};
});
經(jīng)過這樣封裝后,pinia狀態(tài)庫得到解耦,最終的項目結(jié)構(gòu)圖是這樣的:

2. Store組管理
場景分析
大家在項目中是否經(jīng)常遇到某個方法要更新多個store的情況呢?例如:你要做個游戲,有3種職業(yè)「戰(zhàn)士、法師、道士」,另外,玩家角色有3個store來控制「人物屬性、裝備、技能」,頁面有個”轉(zhuǎn)職“按鈕,可以轉(zhuǎn)其他職業(yè)。當(dāng)玩家改變職業(yè)時,3個store的state都要改變,怎么做呢?
- 方法1:在業(yè)務(wù)組件創(chuàng)建個函數(shù),單點擊”轉(zhuǎn)職“時,獲取3個store并且更新它們的值。
- 方法2:抽象一個新pinia store,store里有個”轉(zhuǎn)職“的action,當(dāng)玩家轉(zhuǎn)職時,響應(yīng)這個action,在action更新3個store的值。
對比起來,無論從封裝還是業(yè)務(wù)解耦,明顯方法2更好。要做到這樣,這也得益于pinia的store獨立管理特性,我們只需要把抽象的store作為父store,「人物屬性、裝備、技能」3個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個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個單元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>
效果

落幕
磨刀不誤砍柴工,對于一個項目來講,好的狀態(tài)管理方案在當(dāng)中發(fā)揮重要的作用,不僅能讓項目思路清晰,而且便于項目日后維護和迭代。
項目demo https://github.com/JohnnyZhangQiao/pinia-use
以上就是Pinia進階setup函數(shù)式寫法封裝到企業(yè)項目的詳細內(nèi)容,更多關(guān)于Pinia setup函數(shù)式封裝的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue中使用 setTimeout() setInterval()函數(shù)的問題
這篇文章主要介紹了Vue中使用 setTimeout() setInterval()函數(shù)的問題 ,需要的朋友可以參考下2018-09-09
Vue2+marked.js實現(xiàn)AI流式輸出的項目實踐
本文主要介紹了Vue2+marked.js實現(xiàn)AI流式輸出的項目實踐,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04
vant組件中 dialog的確認按鈕的回調(diào)事件操作
這篇文章主要介紹了vant組件中 dialog的確認按鈕的回調(diào)事件操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

