0
# Pinia
1
2
Pinia is a modern state management library for Vue.js applications that provides an intuitive, type-safe, and flexible store system. It serves as the official successor to Vuex, offering better TypeScript integration, composition API support, and modular design with automatic type inference.
3
4
## Package Information
5
6
- **Package Name**: pinia
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install pinia`
10
11
## Core Imports
12
13
```typescript
14
import { createPinia, defineStore, storeToRefs } from "pinia";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { createPinia, defineStore, storeToRefs } = require("pinia");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { createApp } from "vue";
27
import { createPinia, defineStore } from "pinia";
28
29
// Create and install Pinia
30
const app = createApp({});
31
const pinia = createPinia();
32
app.use(pinia);
33
34
// Define a store with composition API
35
const useCounterStore = defineStore("counter", () => {
36
const count = ref(0);
37
const doubleCount = computed(() => count.value * 2);
38
function increment() {
39
count.value++;
40
}
41
return { count, doubleCount, increment };
42
});
43
44
// Define a store with options API
45
const useUserStore = defineStore("user", {
46
state: () => ({
47
name: "John Doe",
48
email: "john@example.com",
49
}),
50
getters: {
51
displayName: (state) => `${state.name} (${state.email})`,
52
},
53
actions: {
54
updateName(newName: string) {
55
this.name = newName;
56
},
57
},
58
});
59
60
// Use the store in a component
61
const counter = useCounterStore();
62
const user = useUserStore();
63
64
counter.increment();
65
user.updateName("Jane Doe");
66
```
67
68
## Architecture
69
70
Pinia's architecture consists of several key components:
71
72
- **Pinia Instance**: Central application store manager created with `createPinia()`
73
- **Store Definitions**: Reusable store factories created with `defineStore()` supporting both options and setup syntax
74
- **Store Instances**: Runtime store objects with reactive state, computed getters, and action methods
75
- **State Management**: Reactive state with automatic dependency tracking and devtools integration
76
- **Plugin System**: Extensible architecture for adding custom functionality and integrations
77
- **Map Helpers**: Vue Options API compatibility layer for component integration
78
79
## Capabilities
80
81
### Pinia Instance Management
82
83
Core functions for creating and managing the global Pinia instance that coordinates all stores in your application.
84
85
```typescript { .api }
86
function createPinia(): Pinia;
87
function disposePinia(pinia: Pinia): void;
88
function setActivePinia(pinia: Pinia): void;
89
function getActivePinia(): Pinia | undefined;
90
91
interface Pinia {
92
install(app: App): void;
93
use(plugin: PiniaPlugin): Pinia;
94
state: Ref<Record<string, StateTree>>;
95
_p: PiniaPlugin[];
96
_a: App | null;
97
_e: EffectScope;
98
_s: Map<string, StoreGeneric>;
99
}
100
```
101
102
[Pinia Instance Management](./pinia-instance.md)
103
104
### Store Definition
105
106
Functions for defining stores with both composition API (setup function) and options API syntax, providing flexible patterns for different development preferences.
107
108
```typescript { .api }
109
function defineStore<Id extends string, S extends StateTree, G extends _GettersTree<S>, A>(
110
id: Id,
111
options: Omit<DefineStoreOptions<Id, S, G, A>, 'id'>
112
): StoreDefinition<Id, S, G, A>;
113
114
function defineStore<Id extends string, SS>(
115
id: Id,
116
storeSetup: () => SS,
117
options?: DefineSetupStoreOptions<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>
118
): StoreDefinition<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>;
119
120
interface DefineStoreOptions<Id extends string, S extends StateTree, G extends _GettersTree<S>, A> {
121
id: Id;
122
state?: () => S;
123
getters?: G & _GettersTree<S>;
124
actions?: A & _ActionsTree;
125
}
126
```
127
128
[Store Definition](./store-definition.md)
129
130
### Store Usage
131
132
Utilities for working with store instances including extracting reactive references, hydration control, and hot module replacement support.
133
134
```typescript { .api }
135
function storeToRefs<SS extends StoreGeneric>(store: SS): StoreToRefs<SS>;
136
function skipHydrate<T = any>(obj: T): T;
137
function shouldHydrate(obj: any): boolean;
138
function acceptHMRUpdate(store: StoreDefinition, hot: any): (newStore: StoreDefinition) => any;
139
140
type StoreToRefs<SS extends StoreGeneric> = {
141
[K in keyof SS as SS[K] extends (...args: any[]) => any ? never : K]: SS[K] extends Ref
142
? SS[K]
143
: Ref<SS[K]>;
144
};
145
```
146
147
[Store Usage](./store-usage.md)
148
149
### Options API Integration
150
151
Map helper functions that provide compatibility with Vue's Options API, allowing stores to be mapped to component computed properties and methods.
152
153
```typescript { .api }
154
function mapStores<Stores extends any[]>(...stores: [...Stores]): _Spread<Stores>;
155
function mapState<Id extends string, S extends StateTree, G extends _GettersTree<S>, A, Keys extends keyof (S & G)>(
156
useStore: StoreDefinition<Id, S, G, A>,
157
keys: readonly Keys[]
158
): _MapStateReturn<S & G, Keys>;
159
function mapWritableState<Id extends string, S extends StateTree, G extends _GettersTree<S>, A, Keys extends keyof S>(
160
useStore: StoreDefinition<Id, S, G, A>,
161
keys: readonly Keys[]
162
): _MapWritableStateReturn<S, Keys>;
163
function mapGetters<Id extends string, S extends StateTree, G extends _GettersTree<S>, A, Keys extends keyof G>(
164
useStore: StoreDefinition<Id, S, G, A>,
165
keys: readonly Keys[]
166
): _MapStateReturn<G, Keys>;
167
function mapActions<Id extends string, S extends StateTree, G extends _GettersTree<S>, A, Keys extends keyof A>(
168
useStore: StoreDefinition<Id, S, G, A>,
169
keys: readonly Keys[]
170
): _MapActionsReturn<A, Keys>;
171
function setMapStoreSuffix(suffix: string): void;
172
```
173
174
[Options API Integration](./options-api.md)
175
176
## Core Types
177
178
```typescript { .api }
179
type StateTree = Record<PropertyKey, any>;
180
181
interface Store<Id extends string = string, S extends StateTree = {}, G = {}, A = {}> {
182
$id: Id;
183
$state: UnwrapRef<S>;
184
$patch(partialState: _DeepPartial<UnwrapRef<S>>): void;
185
$patch<F extends (state: UnwrapRef<S>) => any>(stateMutator: ReturnType<F> extends Promise<any> ? never : F): void;
186
$reset(): void;
187
$subscribe(callback: SubscriptionCallback<S>, options?: { detached?: boolean } & WatchOptions): () => void;
188
$onAction(callback: StoreOnActionListener<Id, S, G, A>, detached?: boolean): () => void;
189
$dispose(): void;
190
}
191
192
type StoreDefinition<Id extends string = string, S extends StateTree = {}, G = {}, A = {}> = () => Store<Id, S, G, A>;
193
194
type PiniaPlugin = (context: PiniaPluginContext) => Partial<PiniaCustomProperties & PiniaCustomStateProperties> | void;
195
196
interface PiniaPluginContext<Id extends string = string, S extends StateTree = {}, G = {}, A = {}> {
197
pinia: Pinia;
198
app: App;
199
store: Store<Id, S, G, A>;
200
options: DefineStoreOptionsInPlugin<Id, S, G, A>;
201
}
202
203
enum MutationType {
204
direct = 'direct',
205
patchObject = 'patch object',
206
patchFunction = 'patch function',
207
}
208
```