Pro
- supports both vue2 and 3
- abandon
Mutation
, onlystate
,getter
andaction
, simplify state management - no more nested structure, fits composition api style better
- supports TypeScript
- better code splitting
Basic Usage
here lets create a project using vite
:
npm init vite@latest
install pinia
npm i pinia
the entry main.ts
file would be:
and then you can create a store
and use it
when you need to use multiple properties from store
, to make it easier, we can destrcuture them using Pinia's storeToRefs
Pinia State Management
simple data modification can be done using store.propertyName
directly
if the modification involves much data, we can use $patch
, as instructed in its doc, it will improve speed of modification
$patch
accepts two args:
- $patch + object
- $patch + function
you can also make change via action
- add
chagneState
method instore.actions
- call
store.methodName
directly
Getters inside Pinia
the getter
inside pinia
is almost the same to the one in vue
getter
‘s value can be cached, so even if no value change, it will only be called once for multiple calls
- add
getter
method
- use it inside component
inside getter
we can also use this
to modify data
call one store in another
let's create a new store file called substore.ts
and use it in index.ts
Conclusion
well, it is the default recommended by Vue team to replace Vuex, and you can use it in production already.
Top comments (0)