Vue.js State Management
State management is about how your Vue app handles and shares data between components. Vue provides built-in reactivity for local state, props for passing data down, and tools like Vuex or Pinia for managing global state.
1. Local Component State
Each component can manage its own state using data().
2. Parent → Child (Props)
Props let you pass data from parent to child.
3. Child → Parent (Events)
Children can communicate back to the parent using $emit.
4. Global State with Provide/Inject
Vue provides provide and inject for dependency injection, useful for passing state deeply.
5. Pinia (Recommended Global Store)
For large apps, Vue recommends Pinia as the official state management solution.
npm install pinia
// store/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
});
// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
app.use(createPinia());
app.mount('#app');
// In a component
<script setup>
import { useCounterStore } from '../store/counter';
const counter = useCounterStore();
</script>
<template>
<button @click="counter.increment">Count: {{ counter.count }}</button>
</template>
Summary
- Local state: managed inside components with
data() - Props: pass data from parent → child
- Events: send data child → parent
- Provide/Inject: dependency injection for deep hierarchies
- Pinia/Vuex: central global store for large apps