Store 选项式写法
Store 选项式写法是 Pinia 学习中的单个核心知识点,下面直接说明用法。
定义
Store 选项式写法是 Pinia 使用中的一个独立知识点,核心作用是:使用state/actions/getters选项定义Store,理解与Vuex的选项式API对应。
语法
常用语法是在 Store 定义或组件调用处完成配置与使用。
JavaScript
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: { double: (state) => state.count * 2 },
actions: { increment() { this.count++ } }
})
示例
JavaScript
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: { double: (state) => state.count * 2 },
actions: { increment() { this.count++ } }
})
注意事项
保持 Store 职责单一,避免把无关业务状态集中到同一个 Store。
要点总结
Store 选项式写法只解决当前知识点对应的问题。- 优先使用 Pinia 官方 API,避免引入多余封装。
- 示例代码应保持 Store 简洁、职责清晰。
📝 发现内容有误?点击此处直接编辑