Skip to content
sumnail

Pinia の使い方

created at : 2024/08/31

Pinia
Vue3

Pinia の使い方

増加ボタンと減少ボタンの簡易カウンターを作成して、Pinia の基本的な使い方を紹介します。

sample

ボタンを押下するとカウンターが増減します。

Counter: 0

コードは以下の通りです。

カウンターの状態、管理は store で定義しています。

サンプルコード
vue
<template>
  <div>
    <p>Counter: {{ store.counter }}</p>
    <button @click="store.increment">Increment</button>
    <button @click="store.decrement">Decrement</button>
  </div>
</template>

<script setup lang="ts">
import { useCounter } from "../../../.vitepress/theme/stores/counter";

const store = useCounter();
</script>

<style scoped>
p {
  font-size: 20px;
}
button {
  margin: 8px;
  padding: 8px 16px;
  background-color: var(--secondary-color);
  border-radius: 8px;
}
</style>

store の定義

store の定義は以下の通りです。

Setup Stores で定義しています。
Setup Stores は Vue3 の Composition API と同じよう記述することができます。

  • key は counter で、カウンターの状態管理を一意にします。
  • state は refを使用しています。
  • getters は computed を使用しています。
  • actions は methods を使用しています。
ts
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCounter = defineStore("counter", () => {
  const counter = ref(0);
  const doubleCounter = computed(() => counter.value * 2);
  const increment = () => {
    return counter.value++;
  };
  const decrement = () => {
    return counter.value--;
  };

  function $reset() {
    counter.value = 0;
  }

  return { counter, doubleCounter, increment, decrement, $reset };
});

まとめ

Pinia の基本的な使い方を紹介しました。

次のセクションでは、Pinia の基本的な使い方を紹介します。

参考