Pinia is the official state management library for Vue 3. It replaces Vuex with a simpler, type-safe API that feels like writing a Composition API component.
npm install pinia
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app')
// src/stores/counter.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
// state
const count = ref(0)
// getters
const double = computed(() => count.value * 2)
// actions
function increment() { count.value++ }
function reset() { count.value = 0 }
return { count, double, increment, reset }
})
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<p>Count: {{ counter.count }}</p>
<p>Double: {{ counter.double }}</p>
<button @click="counter.increment">+1</button>
<button @click="counter.reset">Reset</button>
</template>