Pinia Dasar — Vue

Pinia adalah state management library resmi Vue 3. // stores/counter.js export const useCounterStore = defineStore("counter", { state: () => ({ count: 0 }), get

Pinia adalah state management library resmi Vue 3.

// stores/counter.js
export const useCounterStore = defineStore("counter", {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() { this.count++ },
  },
})

Penggunaan di Komponen

Dua gaya utama pemakaian store di komponen:

Gaya 1: Akses lewat variable store (paling aman untuk reactivity):

<script setup>
import { useCounterStore } from "./stores/counter";

const counter = useCounterStore();
</script>

<template>
  <p>{{ counter.count }}</p>
  <p>{{ counter.doubleCount }}</p>
  <button @click="counter.increment">+1</button>
</template>

Gaya 2: Destructuring dengan storeToRefs (kalau mau nama lebih pendek):

<script setup>
import { storeToRefs } from "pinia";
import { useCounterStore } from "./stores/counter";

const counter = useCounterStore();
const { count, doubleCount } = storeToRefs(counter); // tetap reactive
const { increment } = counter;                         // action tidak butuh storeToRefs
</script>

<template>
  <p>{{ count }}</p>
  <p>{{ doubleCount }}</p>
  <button @click="increment">+1</button>
</template>

⚠️ Jangan destructuring langsung dari store (const { count } = useCounterStore()) — nilainya akan kehilangan reactivity. Pakai storeToRefs() untuk state dan getter; action boleh di-destructure biasa.

Pinia lebih ringan dari Vuex dan fully typed.

Yang akan kamu pelajari