Pinia 的 Setup Stores 語法太香了
作者:pany 原文:https://juejin.cn/post/7143504636496855077
關(guān)于大菠蘿
如果你還不了解 Pinia,那你可以將它理解為 Vuex5(因?yàn)?Vuex 5 不會(huì)出了),是 Vue3 全家桶成員之一。
這里是它的英文官方文檔[1],中文文檔好像不是官方的,并且當(dāng)前翻譯的不全面(比如 Setup Stores 就沒有在中文文檔中出現(xiàn)),不是很推薦。
先來看看最常見的 Option Stores 語法
傳遞帶有 state、getters 和 actions 屬性的 Options 對(duì)象給 defineStore() 就可以定義一個(gè) Store:
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})
這種語法與 Vuex 中定義 Store 的語法非常近似,但是少了 Mutation 字段。
不僅如此,這種寫法也和 Vue2 的 Options API(選項(xiàng)式 API)結(jié)構(gòu)類似:state 與 data 對(duì)應(yīng)、getters 與 computed 對(duì)應(yīng)、actions 與 methods 對(duì)應(yīng)。
這種寫法的好處就是結(jié)構(gòu)非常清晰,容易上手,特別是對(duì)剛從 Vue2 和 Vuex 轉(zhuǎn)到 Pinia 的開發(fā)者!
安利 Setup Stores 語法
但 Setup Stores 語法更靈活、更函數(shù):
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
在這種語法中,ref 與 state 對(duì)應(yīng)、computed 與 getters 對(duì)應(yīng)、function 與 actions 對(duì)應(yīng)。
想必寫過 Vue3 朋友就能一眼看出來這和 Vue3 新推出的 Composition API(組合式 API)非常類似!這樣的話,在使用 Vue3 和 Pinia 的時(shí)候,就能統(tǒng)一語法了。
如果在 Vue3 的 Setup 語法外使用 Pinia 呢?
如果你準(zhǔn)備在 Vue3 的 Setup 語法外引入 Pinia 的 Store,例如 useCounterStore。
直接 import { useCounterStore } from "@/store/modules/xxxxxx" 是不行的,你得像這樣:
import store from "@/store"
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
/** 在 setup 外使用 */
export function useCounterStoreHook() {
return useCounterStore(store)
}
然后引入 import { useCounterStoreHook } from "@/store/modules/xxxxxx" 即可!
參考資料
https://pinia.vuejs.org/: https://link.juejin.cn?target=https%3A%2F%2Fpinia.vuejs.org%2F
最后
如果你覺得這篇內(nèi)容對(duì)你挺有啟發(fā),我想邀請(qǐng)你幫我個(gè)小忙:
點(diǎn)個(gè)「喜歡」或「在看」,讓更多的人也能看到這篇內(nèi)容
我組建了個(gè)氛圍非常好的前端群,里面有很多前端小伙伴,歡迎加我微信「sherlocked_93」拉你加群,一起交流和學(xué)習(xí)
關(guān)注公眾號(hào)「前端下午茶」,持續(xù)為你推送精選好文,也可以加我為好友,隨時(shí)聊騷。

