pinia-store
Pinia Store 架構規範。Use when creating app/stores/**/*.ts files, working with defineStore, managing global state, or building Pinia stores. Always use this skill for store design patterns, naming conventions, and state management architecture.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
Pinia Store 架構規範
目錄結構
app/stores/
├── userPreferences.ts # 使用者偏好設定
├── auth.ts # 認證狀態
└── ui.ts # UI 全域狀態
Store 模板
使用 Composition API 語法:
import { defineStore } from 'pinia'
export const useMyStore = defineStore('my-store', () => {
const items = ref<Item[]>([])
const isLoading = ref(false)
const error = ref<Error | null>(null)
const itemCount = computed(() => items.value.length)
async function loadItems() {
isLoading.value = true
error.value = null
try {
const data = await $fetch('/api/v1/items')
items.value = data
} catch (e) {
error.value = e as Error
} finally {
isLoading.value = false
}
}
return {
items: readonly(items),
isLoading: readonly(isLoading),
error: readonly(error),
itemCount,
loadItems,
}
})
命名規範
- Store 函式:
use<Name>Store - Store ID:
kebab-case
// ✅
export const useUserPreferencesStore = defineStore('user-preferences', ...)
// ❌
export const userPreferencesStore = defineStore('preferences', ...)
使用方式
<script setup lang="ts">
const store = useMyStore()
// 解構保持響應性
const { items, isLoading } = storeToRefs(store)
const { loadItems } = store
</script>
重要原則
- 使用
readonly()保護回傳的狀態,通過 action 修改 - 避免在 Store 中使用
useState,使用ref替代 - 錯誤處理:try/catch + error state + finally 重設 loading
參考資料
| 檔案 | 內容 |
|---|---|
| references/patterns.md | Plugin 自動初始化、Composable 包裝模式 |
檢查清單
- Composition API 語法(
defineStore('id', () => {...})) - 命名遵循
use<Name>Store - 使用
readonly()保護狀態 - 完整錯誤處理(try/catch + error state)
- 需要全域初始化則建立對應 Plugin
- 不使用
useState
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-03-11
- 索引更新时间
- 2026-03-11
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!