Pinia advantage
Pinia is a new Vue state management library, an alternative to Vuex, which is strongly recommended by Yu Creek
- Both Vue2 and Vue3 are supported
- untraditional
Mutation
, onlystate, getter
和action
To simplify the state management library - No need for nested modules, compliance with Vue3’s Composition API, keeping code flat
- TypeScript support
- Code introduction, good automatic code segmentation
Pinia basic use
Initialization project: NPM init vite@latest
Install Pinia: NPM I Pinia
Mount Pinia
Create the Store
The use of the Store
Deconstruction store
When multiple parameters in the store need to be used, to simplify the use of these variables, we usually use a structured way to get all the variable names at once
ES traditional deconstruction (retrieves values, but is not responsive)
Pinia deconstruction method: storeToRefs
Pinia modifies the data state
Simple data modification
Simple data is modified directly by manipulating the store. Property name in the method
Multiple Data Modifications
It is also feasible to modify multiple pieces of data by modifying basic data. However, it has been clearly stated in pinia’s official website that the $patch method is optimized, which will speed up the modification and is of great benefit to performance. Therefore, it is recommended to use $patch when modifying multiple pieces of data
The $patch method can accept two types of arguments, functions and objects
- $patch + object
- $patch + function: when used as a function, the function takes a state argument, which is the state in the store
Modify through Action
-
Add the changeState method to store. actions
-
The component method calls the store. method name
The Getters Pinia
Getters in Pinia are almost the same as computed properties in Vue, doing some logic before getting the State value
-
The value in the getter is cached. If the value does not change, it is called only once after repeated use
- Adding getter methods
- Multiple calls within a component
-
Not only can you pass state directly to change the state of the data in the getter, but you can also use this to change the data
Calls between stores
In Pinia, it is possible to import a store from another store and obtain the state of the imported store by calling the imported Store method
- The new store
- Import allanStore in the original store and get
moveList
- Use in components
mainStore.getAllanStoreList
conclusion
In general, Pinia is a Vuex replacement that is more compatible with Vue2, Vue3, and TypeScript. Mutation was removed on the basis of Vuex and only state, getter and action were retained. Pinia has a cleaner syntax, flat code layout, and compliance with Vue3’s Composition API