State in stores holds shared data that many parts of your app can use. It helps keep your app organized and consistent.
0
0
Defining state in stores in Vue
Introduction
When multiple components need to access or change the same data.
When you want to keep data in one place instead of passing it through many components.
When you want to remember user choices or app settings across pages.
When you want to react to data changes globally in your app.
Syntax
Vue
import { defineStore } from 'pinia' export const useStore = defineStore('storeId', { state: () => ({ count: 0, name: '' }) })
The state is a function returning an object with your data.
The store ID (first argument) should be unique and descriptive.
Examples
A simple store with a
count number starting at 0.Vue
import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }) })
A store holding user name and login status.
Vue
import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ name: '', loggedIn: false }) })
Sample Program
This example creates a store with a count state. The app shows the count and a button to increase it. The count is shared through the store.
Vue
import { createApp } from 'vue' import { createPinia, defineStore } from 'pinia' const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }) }) const App = { template: ` <div> <p>Count: {{ counter.count }}</p> <button @click="counter.count++">Increase</button> </div> `, setup() { const counter = useCounterStore() return { counter } } } const app = createApp(App) app.use(createPinia()) app.mount('#app')
OutputSuccess
Important Notes
Always define state as a function returning an object to avoid shared state between store instances.
Use descriptive store IDs to avoid confusion in bigger apps.
Pinia stores are reactive, so UI updates automatically when state changes.
Summary
Stores hold shared state for your Vue app.
Define state as a function returning an object inside defineStore.
Use stores to keep data consistent and easy to manage across components.