May be you are already learned about global state and the Vuex store in Vue and Nuxt projects. Is there any other store for Vue3. Yes, Pinia
A minimal app is required to try Pinia store, let's create a nuxt3 app.
Setup Pinia store in a Nuxt3 app
A minimal app is required to try Pinia store, let's create a nuxt3 app.
npx nuxi init nuxt3-app
To setup Pinia store add the Nuxt build module configuration, in nuxt-config, may be the yarn installation will already add it for you,lol.
yarn add pinia @pinia/nuxt
The nuxt config will look like this
// nuxt.config.js
export default {
// ... other options
buildModules: [
'@pinia/nuxt',
],
}
Create the store
Go ahead and create store.ts in the src folder. Pinia uses same philosophy of Vuex, the official Vue store.
//store.ts
import { defineStore, acceptHMRUpdate} from 'pinia'
export const useStore = defineStore('storeId', {
// arrow function recommended for full type inference
state: () => {
return {
// all these properties will have their type inferred automatically
counter: 10,
name: 'Eduardo',
isAdmin: true,
}
},
actions:{
hit(){
this.counter++;
}
},
getters:{
getCount:(state)=>state.counter,
getUser: (state)=> {
state.name
}
}
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useStore, import.meta.hot))
}
Accessing the state
Accessing the state / getters / actions in a component by using the useStore. Sorry about mutation they are gone for ever.
//in some component
<script>
import { useStore } from '@/store'
export default {
data() {
return {
store: useStore()
}
},
}
</script>
In the template we can use the reactive store to access actions/ getter/ state.
State
A single state can be accessed as follows
<template>
<div>
{{store.name}}
......
`
Getters
Getters are functions which return the read only state for stores, which can be also accessed with store object and insert in template with my favorite double mustache.
<template>
{{store.getCount}}
......
Actions
Actions are for making something happen, like increasing a count, or validating a user etc.
<v-btn @click="store.hit()">Hit me</v-btn>
Read more Nuxt3 guides
Top comments (5)
How do you hydrate for SSR?
Did you find a solutions for this?
I am creating some object instances but I alwasy get an error on client side saying the function I am trying to call from the object does not exist.
Although I have a "new MyObject()", it seems to handle the instance as a Object therefore it can't find any method I create in the object class.
Getting following error
here is full working example
github.com/manojap/nuxt3-pinia-sto...
Thanks for your article ๐ I just wanted to add some recent updates related to nuxt v3.
buildModules
property is now deprecated, you should consider usingmodule
instead ๐ More info could be found here: github.com/nuxt/framework/blob/643...