Besides Option Stores you can also use Setup Stores to define stores in Pinia. They bring more flexibility as you can create watchers within a store and freely use any composable.
Defining Setup Store
Just like the setup function in the Vue Composition API, a function that sets up reactive properties and methods can be passed, which will return an object containing the properties and methods that should be made available:
In Setup Stores:
ref()
s becomestate
propertiescomputed()
s becomegetters
function()
s becomeactions
What syntax should I pick?
When it comes to Vue's Composition API and Options API, select the one that you are most familiar with. If you are uncertain, start with the Option Stores.
Using Setup Store
At this point, we only defined the store but it won't be created until use...Store()
is called inside of setup()
:
Info
The store
object has been wrapped with reactive
, so there is no need to include .value
when using getters, but similar to props
in setup
, it cannot be destructured. You need to use storeToRefs()
to destructure while keeping reactivity.
Bonus Tip
You can use composables that return writable state like VueUse useLocalStorage() directly within the state()
function:
The same example using Option Store:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Adding a Latest Route
Utilizing Nuxt Middleware, you can implement an easy way for visitors to always read the latest blog posts (or any other content) without needing to know its name or specific URL.
Nuxt Tip: Analyse Production Bundle
Nuxi analyze is an experimental feature that builds your Nuxt app and analyses the production bundle.