0
# Component Helpers
1
2
Helper functions for mapping store properties to component computed properties and methods, reducing boilerplate code in Vue components.
3
4
## Capabilities
5
6
### State Mapping
7
8
Map store state to component computed properties.
9
10
```typescript { .api }
11
/**
12
* Map store state to computed properties
13
* @param states - Array of state property names
14
* @returns Object with computed property functions
15
*/
16
function mapState(states: string[]): { [key: string]: Computed };
17
18
/**
19
* Map store state with custom names
20
* @param stateMap - Object mapping component names to state paths
21
* @returns Object with computed property functions
22
*/
23
function mapState(stateMap: Record<string, string>): { [key: string]: Computed };
24
25
/**
26
* Map namespaced store state to computed properties
27
* @param namespace - Module namespace
28
* @param states - Array of state property names
29
* @returns Object with computed property functions
30
*/
31
function mapState(namespace: string, states: string[]): { [key: string]: Computed };
32
33
/**
34
* Map namespaced store state with custom names
35
* @param namespace - Module namespace
36
* @param stateMap - Object mapping component names to state paths
37
* @returns Object with computed property functions
38
*/
39
function mapState(namespace: string, stateMap: Record<string, string>): { [key: string]: Computed };
40
41
/**
42
* Map store state with custom getter functions
43
* @param stateMap - Object mapping names to getter functions
44
* @returns Object with computed property functions
45
*/
46
function mapState<S>(stateMap: Record<string, (state: S, getters: any) => any>): { [key: string]: Computed };
47
48
/**
49
* Map namespaced store state with custom getter functions
50
* @param namespace - Module namespace
51
* @param stateMap - Object mapping names to getter functions
52
* @returns Object with computed property functions
53
*/
54
function mapState<S>(namespace: string, stateMap: Record<string, (state: S, getters: any) => any>): { [key: string]: Computed };
55
```
56
57
**Usage Examples:**
58
59
```typescript
60
import { mapState } from 'vuex';
61
62
// Options API component
63
export default {
64
computed: {
65
// Array form - maps to same names
66
...mapState(['count', 'user']),
67
// Equivalent to:
68
// count() { return this.$store.state.count; }
69
// user() { return this.$store.state.user; }
70
71
// Object form - custom names
72
...mapState({
73
localCount: 'count',
74
currentUser: 'user'
75
}),
76
77
// Function form - custom computation
78
...mapState({
79
countPlusOne: state => state.count + 1,
80
userDisplayName: (state, getters) =>
81
state.user ? state.user.name : 'Guest'
82
}),
83
84
// Namespaced module
85
...mapState('cart', ['items', 'total']),
86
...mapState('user', {
87
profile: 'profile',
88
preferences: 'settings.preferences'
89
})
90
}
91
};
92
```
93
94
### Getter Mapping
95
96
Map store getters to component computed properties.
97
98
```typescript { .api }
99
/**
100
* Map store getters to computed properties
101
* @param getters - Array of getter names
102
* @returns Object with computed property functions
103
*/
104
function mapGetters(getters: string[]): { [key: string]: Computed };
105
106
/**
107
* Map store getters with custom names
108
* @param getterMap - Object mapping component names to getter names
109
* @returns Object with computed property functions
110
*/
111
function mapGetters(getterMap: Record<string, string>): { [key: string]: Computed };
112
113
/**
114
* Map namespaced store getters to computed properties
115
* @param namespace - Module namespace
116
* @param getters - Array of getter names
117
* @returns Object with computed property functions
118
*/
119
function mapGetters(namespace: string, getters: string[]): { [key: string]: Computed };
120
121
/**
122
* Map namespaced store getters with custom names
123
* @param namespace - Module namespace
124
* @param getterMap - Object mapping component names to getter names
125
* @returns Object with computed property functions
126
*/
127
function mapGetters(namespace: string, getterMap: Record<string, string>): { [key: string]: Computed };
128
```
129
130
**Usage Examples:**
131
132
```typescript
133
import { mapGetters } from 'vuex';
134
135
export default {
136
computed: {
137
// Array form
138
...mapGetters(['isLoggedIn', 'userDisplayName']),
139
140
// Object form with custom names
141
...mapGetters({
142
loggedIn: 'isLoggedIn',
143
userName: 'userDisplayName'
144
}),
145
146
// Namespaced getters
147
...mapGetters('cart', ['total', 'itemCount']),
148
...mapGetters('user', {
149
hasProfile: 'hasCompletedProfile',
150
avatarUrl: 'profileAvatarUrl'
151
})
152
}
153
};
154
```
155
156
### Mutation Mapping
157
158
Map store mutations to component methods.
159
160
```typescript { .api }
161
/**
162
* Map store mutations to methods
163
* @param mutations - Array of mutation names
164
* @returns Object with method functions
165
*/
166
function mapMutations(mutations: string[]): { [key: string]: MutationMethod };
167
168
/**
169
* Map store mutations with custom names
170
* @param mutationMap - Object mapping component names to mutation names
171
* @returns Object with method functions
172
*/
173
function mapMutations(mutationMap: Record<string, string>): { [key: string]: MutationMethod };
174
175
/**
176
* Map namespaced store mutations to methods
177
* @param namespace - Module namespace
178
* @param mutations - Array of mutation names
179
* @returns Object with method functions
180
*/
181
function mapMutations(namespace: string, mutations: string[]): { [key: string]: MutationMethod };
182
183
/**
184
* Map namespaced store mutations with custom names
185
* @param namespace - Module namespace
186
* @param mutationMap - Object mapping component names to mutation names
187
* @returns Object with method functions
188
*/
189
function mapMutations(namespace: string, mutationMap: Record<string, string>): { [key: string]: MutationMethod };
190
191
/**
192
* Map store mutations with custom functions
193
* @param mutationMap - Object mapping names to functions receiving commit
194
* @returns Object with method functions
195
*/
196
function mapMutations(mutationMap: Record<string, (commit: Commit, ...args: any[]) => any>): { [key: string]: MutationMethod };
197
198
/**
199
* Map namespaced store mutations with custom functions
200
* @param namespace - Module namespace
201
* @param mutationMap - Object mapping names to functions receiving commit
202
* @returns Object with method functions
203
*/
204
function mapMutations(namespace: string, mutationMap: Record<string, (commit: Commit, ...args: any[]) => any>): { [key: string]: MutationMethod };
205
206
type MutationMethod = (...args: any[]) => void;
207
```
208
209
**Usage Examples:**
210
211
```typescript
212
import { mapMutations } from 'vuex';
213
214
export default {
215
methods: {
216
// Array form
217
...mapMutations(['increment', 'decrement']),
218
// Equivalent to:
219
// increment(payload) { this.$store.commit('increment', payload); }
220
221
// Object form with custom names
222
...mapMutations({
223
add: 'increment',
224
subtract: 'decrement'
225
}),
226
227
// Function form for custom logic
228
...mapMutations({
229
incrementBy: (commit, amount) => commit('increment', amount),
230
reset: (commit) => {
231
commit('setCount', 0);
232
commit('clearHistory');
233
}
234
}),
235
236
// Namespaced mutations
237
...mapMutations('cart', ['addItem', 'removeItem']),
238
...mapMutations('user', {
239
updateProfile: 'setProfile',
240
clearSession: 'logout'
241
})
242
}
243
};
244
```
245
246
### Action Mapping
247
248
Map store actions to component methods.
249
250
```typescript { .api }
251
/**
252
* Map store actions to methods
253
* @param actions - Array of action names
254
* @returns Object with method functions
255
*/
256
function mapActions(actions: string[]): { [key: string]: ActionMethod };
257
258
/**
259
* Map store actions with custom names
260
* @param actionMap - Object mapping component names to action names
261
* @returns Object with method functions
262
*/
263
function mapActions(actionMap: Record<string, string>): { [key: string]: ActionMethod };
264
265
/**
266
* Map namespaced store actions to methods
267
* @param namespace - Module namespace
268
* @param actions - Array of action names
269
* @returns Object with method functions
270
*/
271
function mapActions(namespace: string, actions: string[]): { [key: string]: ActionMethod };
272
273
/**
274
* Map namespaced store actions with custom names
275
* @param namespace - Module namespace
276
* @param actionMap - Object mapping component names to action names
277
* @returns Object with method functions
278
*/
279
function mapActions(namespace: string, actionMap: Record<string, string>): { [key: string]: ActionMethod };
280
281
/**
282
* Map store actions with custom functions
283
* @param actionMap - Object mapping names to functions receiving dispatch
284
* @returns Object with method functions
285
*/
286
function mapActions(actionMap: Record<string, (dispatch: Dispatch, ...args: any[]) => any>): { [key: string]: ActionMethod };
287
288
/**
289
* Map namespaced store actions with custom functions
290
* @param namespace - Module namespace
291
* @param actionMap - Object mapping names to functions receiving dispatch
292
* @returns Object with method functions
293
*/
294
function mapActions(namespace: string, actionMap: Record<string, (dispatch: Dispatch, ...args: any[]) => any>): { [key: string]: ActionMethod };
295
296
type ActionMethod = (...args: any[]) => Promise<any>;
297
```
298
299
**Usage Examples:**
300
301
```typescript
302
import { mapActions } from 'vuex';
303
304
export default {
305
methods: {
306
// Array form
307
...mapActions(['fetchUser', 'updateUser']),
308
// Equivalent to:
309
// fetchUser(payload) { return this.$store.dispatch('fetchUser', payload); }
310
311
// Object form with custom names
312
...mapActions({
313
getUser: 'fetchUser',
314
saveUser: 'updateUser'
315
}),
316
317
// Function form for custom logic
318
...mapActions({
319
loadUserProfile: (dispatch, userId) =>
320
dispatch('fetchUser', userId).then(user =>
321
dispatch('fetchUserPreferences', user.id)
322
),
323
refreshData: async (dispatch) => {
324
await dispatch('clearCache');
325
await dispatch('fetchInitialData');
326
}
327
}),
328
329
// Namespaced actions
330
...mapActions('cart', ['addItem', 'checkout']),
331
...mapActions('user', {
332
login: 'authenticate',
333
logout: 'signOut'
334
}),
335
336
// Using mapped actions
337
async handleLogin() {
338
try {
339
await this.login(credentials);
340
this.$router.push('/dashboard');
341
} catch (error) {
342
this.showError(error.message);
343
}
344
}
345
}
346
};
347
```
348
349
### Namespaced Helpers
350
351
Create pre-bound helper functions for a specific namespace.
352
353
```typescript { .api }
354
/**
355
* Create pre-bound helper functions for a specific namespace
356
* @param namespace - Module namespace
357
* @returns Object with namespaced helper functions
358
*/
359
function createNamespacedHelpers(namespace: string): NamespacedMappers;
360
361
interface NamespacedMappers {
362
mapState: Mapper<Computed> & MapperForState;
363
mapMutations: Mapper<MutationMethod> & MapperForMutation;
364
mapGetters: Mapper<Computed>;
365
mapActions: Mapper<ActionMethod> & MapperForAction;
366
}
367
```
368
369
**Usage Examples:**
370
371
```typescript
372
import { createNamespacedHelpers } from 'vuex';
373
374
// Create helpers for 'user' namespace
375
const { mapState, mapActions, mapMutations } = createNamespacedHelpers('user');
376
377
export default {
378
computed: {
379
// These automatically use the 'user' namespace
380
...mapState(['profile', 'preferences']),
381
...mapGetters(['isAuthenticated', 'displayName'])
382
},
383
methods: {
384
...mapMutations(['setProfile', 'clearSession']),
385
...mapActions(['login', 'logout', 'updateProfile'])
386
}
387
};
388
389
// Multiple namespaced helpers
390
const userHelpers = createNamespacedHelpers('user');
391
const cartHelpers = createNamespacedHelpers('cart');
392
393
export default {
394
computed: {
395
...userHelpers.mapState(['profile']),
396
...cartHelpers.mapState(['items', 'total'])
397
},
398
methods: {
399
...userHelpers.mapActions(['login']),
400
...cartHelpers.mapActions(['addItem', 'checkout'])
401
}
402
};
403
```
404
405
### Mixed Helper Example
406
407
Combine different helper types in a single component.
408
409
**Usage Examples:**
410
411
```typescript
412
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
413
414
export default {
415
computed: {
416
// Global state
417
...mapState(['loading', 'error']),
418
419
// Global getters
420
...mapGetters(['isReady', 'currentRoute']),
421
422
// User module state
423
...mapState('user', {
424
userProfile: 'profile',
425
userPrefs: 'preferences'
426
}),
427
428
// Cart module getters
429
...mapGetters('cart', ['itemCount', 'total']),
430
431
// Custom computed
432
canCheckout() {
433
return this.isReady && this.itemCount > 0 && this.userProfile;
434
}
435
},
436
437
methods: {
438
// Global mutations
439
...mapMutations(['setLoading', 'setError']),
440
441
// Global actions
442
...mapActions(['initialize', 'cleanup']),
443
444
// User module actions
445
...mapActions('user', {
446
signIn: 'login',
447
signOut: 'logout'
448
}),
449
450
// Cart module mutations and actions
451
...mapMutations('cart', ['clearCart']),
452
...mapActions('cart', ['checkout']),
453
454
// Custom method using mapped helpers
455
async handleCheckout() {
456
this.setLoading(true);
457
try {
458
const result = await this.checkout();
459
if (result.success) {
460
this.clearCart();
461
this.$router.push('/order-confirmation');
462
}
463
} catch (error) {
464
this.setError(error.message);
465
} finally {
466
this.setLoading(false);
467
}
468
}
469
}
470
};
471
```