Setup Store 標準
13.1.1. Pinia 使用原則
- 状態管理は Pinia を使用します。Vuex は使用しません。
- Setup Store 構文を使用します。Options Store 構文は使用しません。
- Store ファイルは
src/stores/ディレクトリに配置します。 - ファイル名は
use{ドメイン}Store.ts形式に従います。
13.1.2. Setup Store 構造
Setup Store は Composition API の setup() 関数と同じ方式で記述します。
ref()→ statecomputed()→ gettersfunction→ actions
typescript
// src/stores/useUserStore.ts
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { fetchCurrentUser } from '@/api/user'
import type { User } from '@/types/user'
export const useUserStore = defineStore('user', () => {
// state
const user = ref<User | null>(null)
const loading = ref(false)
// getters
const isLoggedIn = computed(() => user.value !== null)
const displayName = computed(() => user.value?.name ?? 'ゲスト')
// actions
async function loadCurrentUser() {
loading.value = true
try {
user.value = await fetchCurrentUser()
} finally {
loading.value = false
}
}
function logout() {
user.value = null
}
return { user, loading, isLoggedIn, displayName, loadCurrentUser, logout }
})13.1.3. Store 初期化
- Pinia インスタンスは
main.tsで生成し、Vue アプリに登録します。 - アプリ起動時に必要な初期データの読み込みは
App.vueのonMountedで実行します。
typescript
// src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')13.1.4. Store 使用原則
- グローバルに共有すべき状態のみ Store に配置します。
- コンポーネントのローカル状態は
ref/reactiveで管理します。 - Store 間の直接参照は最小化します。
| 状態タイプ | 管理方式 | 例 |
|---|---|---|
| グローバル状態 | Pinia Store | ログインユーザー、権限情報、テーマ設定 |
| ページ状態 | コンポーネント ref | フォーム入力値、ローディング状態、モーダル表示有無 |
| サーバー状態 | Composable | API レスポンスデータ、ページネーション |