1. Pinia
1. Introduction
Pinia is the officially recommended state management library, a lightweight alternative to Vuex, with a simpler design, more powerful feature, and supports modular and TypeScript.
2. The main features of Pinia
-
Simple and easy to use:
The API is designed in an intuitive way and deeply integrated with the Vue Composition API.
-
Support modularity:
Each store is managed independently, reducing global store complexity.
-
Hot update:
Supports HMR (Hot Module Replacement) and does not require manual refresh during development.
-
Support TypeScript:
Provides better type derivation and code prompts.
-
No dependency:
No additional plugins or middleware is required, and integration is easier.
2. Pinia Plugin PersistedState
1. Introduction
pinia-plugin-persistedstate is a plugin for Pinia that persists storage state. It saves the status of the store in localStorage or sessionStorage, and the status will still be restored even if the page is refreshed or closed and opens again.
2. Plug-in features
- Supports storage to localStorage or sessionStorage.
- Selectively persist certain stores or fields.
- Simple integration, automatic synchronization of state.
- Supports custom serialization (such as JSON) and deserialization logic.
3. PersistedState configuration item
The persist field is used to configure the policy for persistent storage.
Common configuration items
Configuration Items | type | default value | describe |
---|---|---|---|
enabled | boolean | false | Whether to enable persistent storage. |
key | string | Store Name | The key name stored in Storage. |
storage | Storage | localStorage | Storage method, optional localStorage or sessionStorage. |
paths | string[] | undefined | Selectively persist certain fields (if not set, all are stored by default). |
serializer | object | Built-in JSON serializer | Custom serializers, including serialize and deserialize. |
4. Example: Selective persistence fields
If you just want to persist the name field:
persist: { enabled: true, strategies: [ { key: 'user', storage: localStorage, paths: ['name'], // Persist only `name` }, ], },
5. Example: Custom Serializer
If you need to customize the storage format (such as Base64):
persist: { enabled: true, strategies: [ { key: 'user', storage: sessionStorage, serializer: { serialize: (value) => btoa((value)), // Base64 encoding deserialize: (value) => (atob(value)), // Base64 decoding }, }, ], },
3. How to use Pinia and PersistedState in your project
1. Install the Pinia and PersistedState plug-ins
npm install pinia pinia-plugin-persistedstate
2. Configure Pinia
In the entry file of the project (such as or ):
import { createApp } from 'vue'; import { createPinia } from 'pinia'; import piniaPluginPersistedState from 'pinia-plugin-persistedstate'; import App from './'; const app = createApp(App); // Create a Pinia instanceconst pinia = createPinia(); // Use persistent plug-in(piniaPluginPersistedState); (pinia); ('#app');
3. Create Store
Create a persistent Pinia store, such as src/stores/:
import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', () => { const name = ref('Wang Qiang') const age = ref(25) function setName(name: string) { = name } return { name, age, setName } }, { persist: { storage: sessionStorage } } )
4. Use Store
1. Read
<template> <div> <p>username:{{ }}</p> <button @click="updateName">修改username</button> </div> </template> <script lang="ts" setup> import { useUserStore } from '@/stores/user'; const userStore = useUserStore(); const updateName = () => { ('Zhang San'); }; </script>
2. Update
// Modify directly = 'Zhang San' // Modify through $patch({}) batch objectuserStore.$patch({ name: 'Zhang San', age:19 }) // Modify through the $patch((state) => {}) callback functionuserStore.$patch((state) => { = 'Zhang San' = 19 }) // Modify by action('Zhang San');
3. Reset
Reset state in store to initial value
userStore.$reset()
4. Deconstruct storeToRefs
Deconstruction will lose the responsiveness and need to use storeToRefs to convert it to responsiveness.
import { storeToRefs } from 'pinia' const userStore = useUsersStore() const { name } = storeToRefs(userStore)
5. Listen to state changes
Listen to state changes
/** * When any value in state changes, the function will be triggered * * args: New and old values will be recorded * state: is an instance of the current operation state * options: is an object, such as detached, which is a boolean parameter. When this parameter is true, it indicates that even after the current component is destroyed, it will continue to monitor the changes in the value in state. Optional */ userStore.$subscribe((args, state) => { ('args', args) ('state', state) },{ detached: true })
6. Listen to action calls
When the function is called, the function will be triggered
/** * When calling the function in actions, the function change will be triggered * * args: receive parameters, encapsulating multiple apis: *: Function logic will be executed only after the execution of the logic in $onAction, so the position of the placement is irrelevant to the execution order. *: When an error occurs when calling the function in actions, the function will also be executed. *: Receive the parameters passed by the function in the call actions, which is an array *: The name of the function in the executed actions * detached: This is a boolean parameter. When this parameter is true, it indicates that even when the current component is destroyed, the function calls in actions will continue to be monitored. Optional */ userStore.$onAction((args) => { (() => ("", "====")); ("args", args); }, true);
Summarize
This is the article about the introduction of pinia and pinia-plugin-persistedstate in the Vue3+Vite project. For more related content about Vue3+Vite introduction of pinia and pinia-plugin-persistedstate, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!