相信在座各位假如使用Vue生態(tài)開發(fā)項目情況下渊季,對Pinia狀態(tài)管理庫應該有所聽聞或正在使用菲驴,假如還沒接觸到Pinia蜡娶,這篇文章可以幫你快速入門,并如何在企業(yè)項目中更優(yōu)雅封裝使用纳像。
本文先給大家闡述如何去理解、使用Pinia拯勉,最后講怎樣把Pinia集成到工程中竟趾,適合大多數讀者,至于研讀Pinia的源碼等進階科普宫峦,會另外開一篇文章細述岔帽。另外,本文的所有demo导绷,都專門開了個GitHub項目來保存犀勒,有需要的同學可以拿下來實操一下。????
認識Pinia
Pinia
讀音:/pi?nj?/妥曲,是Vue官方團隊推薦代替Vuex
的一款輕量級狀態(tài)管理庫贾费。 它最初的設計理念是讓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 被調度為常規(guī)的函數調用,而不是使用 dispatch 方法或 MapAction 輔助函數陌宿,這在 Vuex 中很常見
- 支持多個Store
- 支持 Vue devtools锡足、SSR 和 webpack 代碼拆分
Pinia與Vuex代碼分割機制
上述的Pinia輕量有一部分體現在它的代碼分割機制中。
舉個例子:某項目有3個store「user壳坪、job舶得、pay」,另外有2個路由頁面「首頁爽蝴、個人中心頁」沐批,首頁用到job store纫骑,個人中心頁用到了user store,分別用Pinia和Vuex對其狀態(tài)管理九孩。
先看Vuex的代碼分割: 打包時先馆,vuex會把3個store合并打包,當首頁用到Vuex時躺彬,這個包會引入到首頁一起打包煤墙,最后輸出1個js chunk。這樣的問題是宪拥,其實首頁只需要其中1個store仿野,但其他2個無關的store也被打包進來,造成資源浪費她君。
Pinia的代碼分割: 打包時脚作,Pinia會檢查引用依賴,當首頁用到job store缔刹,打包只會把用到的store和頁面合并輸出1個js chunk球涛,其他2個store不耦合在其中。Pinia能做到這點桨螺,是因為它的設計就是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技術棧開發(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的編程模式,讓結構更加扁平化骏融,個人推薦推薦使用這種方式链嘀。
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è)務方調用來改變state的入口霹琼,getters是獲取state的計算結果。
之所以用第一種方式定義是還要額外寫getters
、action
關鍵字來區(qū)分枣申,是因為在options API模式下可以通過mapState()
售葡、mapActions()
等方法獲取對應項;但第二種方式就可以直接獲取了(下面會細述)忠藤。
4. 業(yè)務組件對store的調用
在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">
<h1>Setup模式</h1>
<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模式下的調用機制是先install再調用。
install這樣寫:
const counterStoreForSetup = useCounterStoreForSetup();
熄驼,其中useCounterStoreForSetup
就是你定義store的變量像寒;調用就直接用
counterStoreForSetup.xxx
(xxx包括:state、getters瓜贾、action)就好。代碼中獲取state是用了解構賦值携悯,為了保持state的響應式特性祭芦,需要用
storeToRefs
進行包裹。
兼容Vue2的Options API調用方式可以到 這里憔鬼。
5. 良好的編程習慣
state的改變交給action去處理: 上面例子龟劲,counterStoreForSetup
有個pinia實例屬性叫$state
是可以直接改變state的值,但不建議怎么做轴或。一是難維護昌跌,在組件繁多情況下,一處隱蔽state更改照雁,整個開發(fā)組幫你排查蚕愤;二是破壞store封裝,難以移植到其他地方饺蚊。所以萍诱,為了你的聲譽和安全著想,請停止游離之外的coding????污呼。
用hook代替pinia實例屬性: install后的counterStoreForSetup
對象里面裕坊,帶有不少$
開頭的方法,其實這些方法大多數都能通過hook引入代替燕酷。
其他的想到再補充...
企業(yè)項目封裝攻略
1. 全局注冊機
重復打包問題
在上面的例子我們可以知道籍凝,使用store時要先把store的定義import進來,再執(zhí)行定義函數使得實例化苗缩。但是饵蒂,在項目逐漸龐大起來后,每個組件要使用時候都要實例化嗎挤渐?在文中開頭講過苹享,pinia的代碼分割機制是把引用它的頁面合并打包,那像下面的例子就會有問題,user被多個頁面引用得问,最后user store被重復打包囤攀。
為了解決這個問題,我們可以引入 ”全局注冊“ 的概念宫纬。做法如下:
創(chuàng)建總入口
在src/store目錄下創(chuàng)建一個入口index.ts焚挠,其中包含一個注冊函數registerStore(),其作用是把整個項目的store都提前注冊好漓骚,最后把所有的store實例掛到appStore透傳出去蝌衔。這樣以后,只要我們在項目任何組件要使用pinia時蝌蹂,只要import appStore進來噩斟,取對應的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è)務組件內直接使用
// 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">
<h1>Setup模式</h1>
<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實例與項目解耦剃允,在構建時要把appStore抽取到公共chunk,在vite.config.ts做如下配置
export default defineConfig(({ command }: ConfigEnv) => {
return {
// ...其他配置
build: {
// ...其他配置
rollupOptions: {
output: {
manualChunks(id) {
// 將pinia的全局庫實例打包進vendor齐鲤,避免和頁面一起打包造成資源重復引入
if (id.includes(path.resolve(__dirname, '/src/store/index.ts'))) {
return 'vendor';
}
}
}
}
}
};
});
復制代碼
經過這樣封裝后斥废,pinia狀態(tài)庫得到解耦,最終的項目結構圖是這樣的:
2. Store組管理
場景分析
大家在項目中是否經常遇到某個方法要更新多個store的情況呢给郊?例如:你要做個游戲牡肉,有3種職業(yè)「戰(zhàn)士、法師淆九、道士」统锤,另外,玩家角色有3個store來控制「人物屬性吩屹、裝備跪另、技能」,頁面有個”轉職“按鈕煤搜,可以轉其他職業(yè)免绿。當玩家改變職業(yè)時,3個store的state都要改變擦盾,怎么做呢嘲驾?
- 方法1:在業(yè)務組件創(chuàng)建個函數,單點擊”轉職“時迹卢,獲取3個store并且更新它們的值辽故。
- 方法2:抽象一個新pinia store,store里有個”轉職“的action腐碱,當玩家轉職時誊垢,響應這個action掉弛,在action更新3個store的值。
對比起來喂走,無論從封裝還是業(yè)務解耦殃饿,明顯方法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', () => {
// 注冊組內store
const basic = roleBasic();
const equipment = roleEquipment();
const skill = roleSkill();
// 轉職業(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è)務組件調用
<script setup lang="ts" name="component-StoreGroup">
import appStore from '@/store';
</script>
<template>
<div class="box-styl">
<h1>Store組管理</h1>
<div class="section-box">
<p>
當前職業(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>轉職:</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)管理方案在當中發(fā)揮重要的作用,不僅能讓項目思路清晰焕檬,而且便于項目日后維護和迭代姆坚。