About Big Pineapple
If you don't know Pinia yet, you can understand it as Vuex5 (because Vuex 5 won't come out), and is one of the Vue3 family bucket members.
Here is itsOfficial English documentation, Chinese documents seem to be not official, and the current translation is not comprehensive (for example, Setup Stores does not appear in Chinese documents), so it is not very recommended.
The most common Option Stores syntax
Pass withstate
、getters
andactions
The Options object of the attribute is givendefineStore()
You can define a Store:
export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { doubleCount: (state) => * 2 }, actions: { increment() { ++ } } })
This syntax andVuex
The syntax of the definition Store in the store is very similar, but it is lessMutation
Field.
Not only that, this way of writing is alsoVue2
The Options API (optional API) structure is similar:state
anddata
correspond,getters
andcomputed
correspond,actions
andmethods
correspond.
The advantage of this writing is that the structure is very clear and easy to get started, especially for developers who have just moved from Vue2 and Vuex to Pinia!
Amway Setup Stores Syntax
But the Setup Stores syntax is more flexible and more functional:
export const useCounterStore = defineStore('counter', () => { const count = ref(0) const doubleCount = computed(() => * 2) function increment() { ++ } return { count, doubleCount, increment } })
In this syntax,ref
andstate
correspond,computed
andgetters
correspond,function
andactions
correspond.
I believe that friends who have written about Vue3 will tell at a glance that this is very similar to Vue3’s newly launched Composition API (combination API)! In this way, you can unify the syntax when using Vue3 and Pinia.
What if you use Pinia outside of Vue3's Setup syntax?
If you are planning to introduce Pinia's Store outside the Setup syntax of Vue3, such as useCounterStore.
directimport { useCounterStore } from "@/store/modules/xxxxxx"
That's not possible, you have to look like this:
import store from "@/store" export const useCounterStore = defineStore('counter', () => { const count = ref(0) const doubleCount = computed(() => * 2) function increment() { ++ } return { count, doubleCount, increment } }) /** Use outside the setup */ export function useCounterStoreHook() { return useCounterStore(store) }
Then introduceimport { useCounterStoreHook } from "@/store/modules/xxxxxx"
Just go!
Integrated Pinia templates
Finally, I would like to recommend this lightweight Vue3 backend management template, which integrates Pinia and the syntax is Setup Stores!
GitHub: v3-admin-vite
Gitee: v3-admin-vite
The above is the detailed explanation of the Pinia Setup Stores syntax example. For more information about Pinia Setup Stores syntax, please follow my other related articles!