File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Create Store Dynamically
2
+
3
+ Store can be created dynamically using factory pattern. Which will greatly help reduce boilerplate and structure your application.
4
+
5
+ ## Example
6
+
7
+ An usecase of multiple tables that require pagination and filter. And all need to have separate stores to keep track of the result and pagings.
8
+
9
+ We can have a creator function like this
10
+
11
+ ``` js
12
+ export const createPagingStore = (endpoint ) => {
13
+ const currentPage = ref (0 )
14
+ const totalPage = ref (0 )
15
+ const tableContent = ref ()
16
+ const fetchData = async (page ) => {
17
+ const data = await api .get (` https://example.com/${ endpoint} ?page=${ page} ` )
18
+ currentPage .value = page
19
+ totalPage .value = data .totalPage
20
+ tableContent = data .content
21
+ }
22
+
23
+ return {currentPage, totalPage, tableContent, fetchData}
24
+ }
25
+ ```
26
+
27
+ Inside the ` defineStore ` option function you will have access to all the state and actions, and extra logic as needed.
28
+
29
+ ``` js
30
+
31
+ export const usePagingWeather = defineStore (' pagingWeather, () => {
32
+ const pagingStore = createPagingStore(' weather' )
33
+
34
+ // Extra logics for this store
35
+ const sundays = computed(() => {
36
+ return pagingStore.tableContent.days.filter(day === ' sunday' )
37
+ })
38
+
39
+ return {
40
+ ...pagingStore,
41
+ sundays,
42
+ }
43
+ })
44
+ ```
45
+
46
+ Don' t worry about the same ` ref` ' s inside multiple store to be the same. They are handled by `pinia` as separate states in the stores.
Original file line number Diff line number Diff line change 4
4
- [ HMR] ( ./hot-module-replacement.md ) : How to activate hot module replacement and improve the developer experience.
5
5
- [ Testing Stores (WIP)] ( ./testing.md ) : How to unit test Stores and mock them in component unit tests.
6
6
- [ Composing Stores] ( ./composing-stores.md ) : How to cross use multiple stores. e.g. using the user store in the cart store.
7
+ - [ Create Store Dynamically] ( ./create-store-dynamically.md ) : An advance usecase for creating store.
7
8
- [ Options API] ( ./options-api.md ) : How to use Pinia without the composition API, outside of ` setup() ` .
8
9
- [ Migrating from 0.0.7] ( ./migration-0-0-7.md ) : A migration guide with more examples than the changelog.
You can’t perform that action at this time.
0 commit comments