0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue 3での状態管理、Piniaの基本的な使い方まとめ

Posted at

こんにちは!今回は、Vue 3の公式状態管理ライブラリ「Pinia」の使い方について、初心者の方向けにわかりやすくまとめました。


✅ 導入手順まとめ

  1. Piniaのインストール

    npm install pinia
    
  2. VueアプリにPiniaを登録

    // main.js に追加
    import { createPinia } from 'pinia'
    app.use(createPinia())
    
  3. ストアを作成

    // src/stores/counter.js に追加
    import { defineStore } from 'pinia'
    
    export const useCounterStore = defineStore('counter', {
      state: () => ({ count: 0 }),
      getters: {
        doubleCount: (state) => state.count * 2
      },
      actions: {
        increment() {
          this.count++
        }
      }
    })
    
  4. コンポーネントでストアを使用

    <!-- src/components/Counter.vue に追加 -->
    <script setup>
    import { useCounterStore } from '@/stores/counter'
    const counter = useCounterStore()
    </script>
    
    <template>
      <p>{{ counter.count }}</p>
      <button @click="counter.increment">+1</button>
    </template>
    

🧹 Piniaとは?

PiniaはVue 3用の公式な状態管理ライブラリで、以下のような特徴があります:

  • 軽量 & シンプルなAPI
  • Composition APIとの高い親和性
  • 型安全(TypeScriptとの相性が良い)
  • Vue Devtoolsに対応

🚀 セットアップ

まずはPiniaをインストールして、Vueアプリに導入しましょう。

1. インストール(ターミナル)

npm install pinia

2. アプリにPiniaを登録(src/main.js

// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)

// PiniaをVueに組み込む
app.use(createPinia())

// アプリをマウントする
app.mount('#app')

🛠 ストアの作成(src/stores/counter.js

次に、ストア(状態を管理する場所)を作ります。

// stores/counter.js
import { defineStore } from 'pinia'

// ストアを定義(名前は 'counter')
export const useCounterStore = defineStore('counter', {
  // 状態(state)を定義
  state: () => ({
    count: 0  // カウントの初期値
  }),
  // ゲッター(算出プロパティ)を定義
  getters: {
    doubleCount: (state) => state.count * 2  // countの2倍を返す
  },
  // アクション(状態を変更する関数)を定義
  actions: {
    increment() {
      this.count++  // countを1増やす
    }
  }
})

各部分の役割

  • state:リアクティブな状態(data)
  • getters:算出プロパティ(computed)
  • actions:状態を変更する関数(methods)

💡 コンポーネントで使ってみよう(例:src/components/Counter.vue

<!-- Counter.vue -->
<script setup>
// ストアをインポート
import { useCounterStore } from '@/stores/counter'

// ストアを使う
const counter = useCounterStore()
</script>

<template>
  <div>
    <!-- ストアの状態を表示 -->
    <p>Count: {{ counter.count }}</p>
    <p>Double: {{ counter.doubleCount }}</p>

    <!-- アクションを呼び出すボタン -->
    <button @click="counter.increment">+1</button>
  </div>
</template>

useCounterStore() を呼ぶだけで、ストアにアクセスできます。とってもシンプル!


📁 ディレクトリ構成

src/
├─ stores/
│   └─ counter.js          # ストア定義ファイル
├─ components/
│   └─ Counter.vue         # UIコンポーネント
├─ App.vue
├─ main.js                # エントリーポイント

📝 まとめ

PiniaはVue 3にとって、非常に使いやすく直感的な状態管理ライブラリです。Vuexよりも学習コストが低いため、これからVueを学ぶ方には特におすすめです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?