# SimulationPinia **Repository Path**: QQXQQ/SimulationPinia ## Basic Information - **Project Name**: SimulationPinia - **Description**: 模拟Pinia - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-07-26 - **Last Updated**: 2026-02-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: JavaScript ## README # SimulationPinia 模拟 Pinia 的轻量级状态管理库 ## 介绍 SimulationPinia 是一个使用 TypeScript 和 Vue 3 实现的 Pinia 状态管理库模拟项目。该项目完整还原了 Pinia 的核心功能,包括: - **Store 定义**:支持选项式(Options API)和组合式(Setup API)两种方式定义 Store - **状态管理**:响应式状态、计算属性、Actions - **订阅机制**:支持 actions 订阅 - **辅助函数**:提供 `mapState`、`mapActions`、`mapWritableState` 等工具函数 ## 技术栈 - **Vue 3** - 响应式框架 - **TypeScript** - 类型支持 - **Vite** - 构建工具 ## 项目结构 ``` src/ ├── pinia/ # Pinia 核心实现 │ ├── createPinia.ts # 创建 Pinia 实例 │ ├── defineStore.ts # 定义 Store 的核心逻辑 │ ├── index.ts # 入口文件 │ ├── pubSub.ts # 发布/订阅机制 │ ├── rootStore.ts # 根 Store 管理 │ ├── types/ │ │ └── PiniaInstances.ts # 类型定义 │ └── utils.ts # 工具函数 ├── stores/ # 示例 Store │ └── counter.ts # 计数器 Store 示例 ├── App.vue # 根组件 └── main.ts # 入口文件 ``` ## 安装教程 ```bash # 安装依赖 npm install # 启动开发服务器 npm run dev # 构建生产版本 npm run build ``` ## 使用说明 ### 1. 创建 Pinia 实例 ```typescript import { createPinia } from './pinia' const pinia = createPinia() ``` ### 2. 定义 Store(选项式) ```typescript import { defineStore } from './pinia' export const useCounterOptionsStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { doubleCount: (state) => state.count * 2 }, actions: { increment() { this.count++ } } }) ``` ### 3. 定义 Store(组合式) ```typescript import { defineStore } from './pinia' export const useCounterSetupStore = defineStore('counter', () => { const count = ref(0) const doubleCount = computed(() => count.value * 2) function increment() { count.value++ } return { count, doubleCount, increment } }) ``` ### 4. 使用辅助函数 ```typescript import { mapState, mapActions, mapWritableState } from './pinia/utils' // 在组件中 export default { computed: { ...mapState(useCounterStore, ['count', 'doubleCount']), ...mapWritableState(useCounterStore, ['count']) }, methods: { ...mapActions(useCounterStore, ['increment']) } } ``` ### 5. 订阅 Actions ```typescript const store = useCounterStore() store.$subscribe((mutation, state) => { console.log('State changed:', state) }) ``` ## 核心 API | API | 说明 | |------|------| | `createPinia()` | 创建 Pinia 实例 | | `defineStore()` | 定义 Store,支持选项式和组合式 | | `mapState()` | 映射 state 和 getters 到组件计算属性 | | `mapActions()` | 映射 actions 到组件方法 | | `mapWritableState()` | 映射可写 state 到组件计算属性 | ## 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request ## License MIT