全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-06-04 7 分钟 ✍️ juanwangdev

共享 State 模式

共享 State 模式是 Pinia 学习中的单个核心知识点,下面直接说明用法。

定义

共享 State 模式是 Pinia 使用中的一个独立知识点,核心作用是:设计一个共享Store作为多个功能模块的桥梁,掌握避免紧耦合的模式。

语法

常用语法是在 Store 定义或组件调用处完成配置与使用。

JavaScript
export const useUserStore = defineStore('user', {
  state: () => ({
    name: 'Tom',
    token: '',
    roles: []
  })
})

const userStore = useUserStore()
userStore.name = 'Jerry'

示例

JavaScript
export const useUserStore = defineStore('user', {
  state: () => ({
    name: 'Tom',
    token: '',
    roles: []
  })
})

const userStore = useUserStore()
userStore.name = 'Jerry'

注意事项

保持 Store 职责单一,避免把无关业务状态集中到同一个 Store。

要点总结

  • 共享 State 模式 只解决当前知识点对应的问题。
  • 优先使用 Pinia 官方 API,避免引入多余封装。
  • 示例代码应保持 Store 简洁、职责清晰。

📝 发现内容有误?点击此处直接编辑

← 上一篇 避免状态交叉请求污染
下一篇 → 在 Store 中访问其他 Store
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库