Basic introduction
Pinia is a lightweight state management library
Official website:/
- Pinia, like vuex4, is also a vue official state management tool (the author is a member of the Vue core team)
- Pinia has better compatibility with vue3 than vuex4
- Compared with vuex4, pinia has complete types of recommendations
- Pinia also supports vue developer tools, the latest developer tools do not support vuex4
Pinia core concept
- state: status
- actions: Modify state (including synchronization and asynchronous, there are no mutations in pinia)
- getters: calculate attributes
Basic use and state
Objective: Master the steps to use pinia
(1) Installation
yarn add pinia # or npm i pinia
(2) Mount pinia in
import { createApp } from 'vue' import App from './' import { createPinia } from 'pinia' const pinia = createPinia() createApp(App).use(pinia).mount('#app')
(3) Create a new file store/
import { defineStore } from 'pinia' // Create store, naming rules: useXxxxStore// Parameter 1: The unique representation of the store// Parameter 2: object, state actions getters can be providedconst useCounterStore = defineStore('counter', { state: () => { return { count: 0, } }, getters: { }, actions: { }, }) export default useCounterStore
(4) Use in components
<script setup> import useCounterStore from './store/counter' const counter = useCounterStore() </script> <template> <h1>Root Component---{{ }}</h1> </template> <style></style>
Use of actions
Goal: Master the use of actions in pinia
There are no mutations in pinia, only actions. Whether it is synchronous or asynchronous code, it can be done in actions.
(1) Provide methods and modify data in actions
import { defineStore } from 'pinia' // 1. Create a store// Parameter 1: The unique representation of the store// Parameter 2: object, state actions getters can be providedconst useCounterStore = defineStore('counter', { state: () => { return { count: 0, } }, actions: { increment() { ++ }, incrementAsync() { setTimeout(() => { ++ }, 1000) }, }, }) export default useCounterStore
(2) Use in components
<script setup> import useCounterStore from './store/counter' const counter = useCounterStore() </script> <template> <h1>Root Component---{{ }}</h1> <button @click="">add1</button> <button @click="">异步add1</button> </template>
Use of getters
Getters in pinia are basically the same as those in vuex, and also have a cache function
(1) Provide computed attributes in getters
import { defineStore } from 'pinia' // 1. Create a store// Parameter 1: The unique representation of the store// Parameter 2: object, state actions getters can be providedconst useCounterStore = defineStore('counter', { state: () => { return { count: 0, } }, getters: { double() { return * 2 }, }, actions: { increment() { ++ }, incrementAsync() { setTimeout(() => { ++ }, 1000) }, }, }) export default useCounterStore
(2) Use in components
<h1>Root Component---{{ }}</h1> <h3>{{ }}</h3>
Use of storeToRefs
Goal: Master the use of storeToRefs
If you deconstruct data directly from pinia, the responsiveness will be lost. Using storeToRefs can ensure that the deconstructed data is also responsive
<script setup> import { storeToRefs } from 'pinia' import useCounterStore from './store/counter' const counter = useCounterStore() // If you deconstruct data directly from pinia, the responsiveness will be lostconst { count, double } = counter // Using storeToRefs can ensure that the deconstructed data is also responsiveconst { count, double } = storeToRefs(counter) </script>
pinia modular
In complex projects, it is impossible to define the data of multiple modules into a store. Generally speaking, a module corresponds to a store, and finally integrates it through a root store.
(1) Create a new store/file
import { defineStore } from 'pinia' const useUserStore = defineStore('user', { state: () => { return { name: 'zs', age: 100, } }, }) export default useUserStore
(2) Create a new store/
import useUserStore from './user' import useCounterStore from './counter' // Unified export of useStore methodsexport default function useStore() { return { user: useUserStore(), counter: useCounterStore(), } }
(3) Use in components
<script setup> import { storeToRefs } from 'pinia' import useStore from './store' const { counter } = useStore() // Using storeToRefs can ensure that the deconstructed data is also responsiveconst { count, double } = storeToRefs(counter) </script>
pinia data persistence
Target:Quickly implement persistent storage with the Pinia plug-in.
Plugin documentation:Click to view
usage
Install
yarn add pinia-plugin-persistedstate or npm i pinia-plugin-persistedstate
Using plug-insRegister in
import { createApp } from "vue"; import App from "./"; import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia(); (piniaPluginPersistedstate); createApp(App).use(pinia);
Module enables persistence
const useHomeStore = defineStore("home",{ // Turn on data persistence persist: true // ...Omitted});
Frequently Asked Questions
- After the module is persisted, will the data change in the future? What should I do?
- Read the local data first. If a new request obtains new data, the new data will be automatically overwritten with the old data.
- No additional processing is required, the plug-in will update to the latest data by itself.
Advanced usage
Requirements: If you don’t want all data to be processed persistently, can you persist the required data as needed? What should you do?
- The data of certain modules can be cached as needed using configuration writing.
import { defineStore } from 'pinia' export const useStore = defineStore('main', s{ state: () => { return { someState: 'hello pinia', nested: { data: 'nested pinia', }, } }, // All data persistence // persist: true, // Other configurations of persistent storage plug-in persist: { // Modify the key name used in the storage, default to the id of the current Store key: 'storekey', // Modify to sessionStorage, default to localStorage storage: , // Array of dot symbol paths for partially persisted states, [] means that no state is persisted (default is undefined, persisting the entire state) paths: [''], }, })
Summary: Compared with vuex, pinia has better support for typescript, and friendly devTools support. pinia only has 1kb, which simplifies the writing of many methods.
Summarize
This is the end of this article about the simple use of Pinia and detailed explanation of data persistence. For more related content on Pinia data persistence, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!