Pinia 的 Setup Stores 語法使用實例詳解
關于大菠蘿
如果你還不了解 Pinia,那你可以將它理解為 Vuex5(因為 Vuex 5 不會出了),是 Vue3 全家桶成員之一。
這里是它的英文官方文檔,中文文檔好像不是官方的,并且當前翻譯的不全面(比如 Setup Stores 就沒有在中文文檔中出現(xiàn)),不是很推薦。
最常見的 Option Stores 語法
傳遞帶有 state、getters 和 actions 屬性的 Options 對象給 defineStore() 就可以定義一個 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(選項式 API)結構類似:state 與 data 對應、getters 與 computed 對應、actions 與 methods 對應。
這種寫法的好處就是結構非常清晰,容易上手,特別是對剛從 Vue2 和 Vuex 轉到 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 對應、computed 與 getters 對應、function 與 actions 對應。
想必寫過 Vue3 朋友就能一眼看出來這和 Vue3 新推出的 Composition API(組合式 API)非常類似!這樣的話,在使用 Vue3 和 Pinia 的時候,就能統(tǒng)一語法了。
如果在 Vue3 的 Setup 語法外使用 Pinia 呢?
如果你準備在 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" 即可!
集成好 Pinia 的模板
最后自薦一下這個輕量級 Vue3 后臺管理模板,集成好了 Pinia 并且語法正是 Setup Stores!
以上就是Pinia 的 Setup Stores 語法使用實例詳解的詳細內容,更多關于Pinia Setup Stores 語法的資料請關注腳本之家其它相關文章!
相關文章
從vue基礎開始創(chuàng)建一個簡單的增刪改查的實例代碼(推薦)
這篇文章主要介紹了從vue基礎開始創(chuàng)建一個簡單的增刪改查的實例代碼,需要的朋友參考下2018-02-02
vue+elementUI動態(tài)增加表單項并添加驗證的代碼詳解
這篇文章主要介紹了vue+elementUI動態(tài)增加表單項并添加驗證的代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

