Vue.js
Beginner
1 min read
Introduction to Pinia Stores
Example
// src/stores/counter.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
// Composition-API (setup) style store
export const useCounterStore = defineStore('counter', () => {
// State
const count = ref(0);
const step = ref(1);
// Getter (computed)
const doubled = computed(() => count.value * 2);
// Actions
function increment() { count.value += step.value; }
function decrement() { count.value -= step.value; }
function reset() { count.value = 0; }
return { count, step, doubled, increment, decrement, reset };
});
// ── Component usage ───────────────────────────
<script setup>
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
// Access state reactively
console.log(counter.count, counter.doubled);
</script>
<template>
<p>Count: {{ counter.count }} (×2 = {{ counter.doubled }})</p>
<button @click="counter.increment">+</button>
<button @click="counter.decrement">−</button>
<button @click="counter.reset">Reset</button>
</template>