跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Pinia Store定义
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
{{Note|本教程适用于Vue.js开发者,需具备基础JavaScript和Vue 3知识。建议先完成[[Vue.js组件]]章节再学习Pinia。}} = Pinia Store定义 = '''Pinia Store'''是Pinia状态管理库的核心构建块,用于在Vue应用中集中管理全局状态。与Vuex相比,Pinia提供了更简单的API、TypeScript集成和组合式API支持。 == 核心概念 == 一个Pinia Store包含三个关键部分: * <code>state</code>: 类似组件的data() * <code>getters</code>: 类似组件的computed属性 * <code>actions</code>: 类似组件的methods <mermaid> pie title Store结构组成 "State" : 45 "Getters" : 25 "Actions" : 30 </mermaid> == 基础Store定义 == === 选项式语法 === 最基础的Store定义方式(兼容Vue 2/3): <syntaxhighlight lang="javascript"> import { defineStore } from 'pinia' // 使用选项式API export const useCounterStore = defineStore('counter', { // 状态定义 state: () => ({ count: 0, user: null }), // 计算属性 getters: { doubleCount: (state) => state.count * 2, }, // 操作方法 actions: { increment() { this.count++ }, async fetchUser(userId) { this.user = await api.fetchUser(userId) } } }) </syntaxhighlight> === 组合式语法 === Vue 3推荐写法(类似setup()): <syntaxhighlight lang="javascript"> import { defineStore } from 'pinia' import { ref, computed } from 'vue' export const useCounterStore = defineStore('counter', () => { // state const count = ref(0) const user = ref(null) // getters const doubleCount = computed(() => count.value * 2) // actions function increment() { count.value++ } async function fetchUser(userId) { user.value = await api.fetchUser(userId) } return { count, user, doubleCount, increment, fetchUser } }) </syntaxhighlight> == 类型定义(TypeScript) == Pinia提供完整的类型推断: <syntaxhighlight lang="typescript"> interface User { id: number name: string } interface CounterState { count: number user: User | null } export const useCounterStore = defineStore('counter', { state: (): CounterState => ({ count: 0, user: null }), // ...其他选项 }) </syntaxhighlight> == Store实例化 == 在组件中使用Store: <syntaxhighlight lang="vue"> <script setup> import { useCounterStore } from '@/stores/counter' const store = useCounterStore() // 访问state console.log(store.count) // 调用action store.increment() </script> <template> <div>{{ store.doubleCount }}</div> </template> </syntaxhighlight> == 实际应用案例 == === 电商购物车 === <syntaxhighlight lang="javascript"> export const useCartStore = defineStore('cart', { state: () => ({ items: [], discount: 0.1 }), getters: { total: (state) => state.items.reduce( (sum, item) => sum + item.price * item.quantity, 0 ), discountedTotal: (state) => this.total * (1 - state.discount) }, actions: { addItem(product, quantity = 1) { const existing = this.items.find(item => item.id === product.id) existing ? existing.quantity += quantity : this.items.push({ ...product, quantity }) }, applyCoupon(code) { this.discount = validateCoupon(code) ? 0.2 : 0.1 } } }) </syntaxhighlight> === 用户认证 === <syntaxhighlight lang="javascript"> export const useAuthStore = defineStore('auth', () => { const user = ref(null) const isAuthenticated = computed(() => !!user.value) async function login(credentials) { user.value = await api.login(credentials) } function logout() { user.value = null } return { user, isAuthenticated, login, logout } }) </syntaxhighlight> == 最佳实践 == 1. '''命名规范''': 使用<code>useXxxStore</code>命名约定 2. '''单一职责''': 每个Store应只管理一个逻辑领域 3. '''组合Store''': 可通过<code>useStore()</code>调用其他Store 4. '''持久化''': 敏感数据不应直接存在Store中 == 数学表达 == Store状态变化可表示为: <math> S_{t+1} = A(S_t, P) </math> 其中: * <math>S</math> = 状态 * <math>A</math> = action函数 * <math>P</math> = 传入参数 == 常见问题 == {{Warning|不要直接解构Store会失去响应性!}} 错误示范: <syntaxhighlight lang="javascript"> const { count, increment } = useCounterStore() // ✗ 错误 </syntaxhighlight> 正确做法: <syntaxhighlight lang="javascript"> const store = useCounterStore() const count = storeToRefs(store).count // ✓ 正确 </syntaxhighlight> == 总结 == Pinia Store通过清晰的结构定义应用状态: * 使用<code>defineStore()</code>创建 * 支持选项式和组合式API * 天然支持TypeScript * 遵循Vue响应式规则 {{Tip|在大型项目中,建议按功能模块拆分多个Store,而非创建单个全局Store。}} [[Category:前端框架]] [[Category:Vue.js]] [[Category:Pinia状态管理]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)
该页面使用的模板:
模板:Mbox
(
编辑
)
模板:Note
(
编辑
)
模板:Tip
(
编辑
)
模板:Warning
(
编辑
)
模块:Arguments
(
编辑
)
模块:Message box
(
编辑
)
模块:Message box/ambox.css
(
编辑
)
模块:Message box/configuration
(
编辑
)
模块:Yesno
(
编辑
)