1. Introduction to Pinia
Pinia is the official recommended state management library for Vue 3, designed to replace Vuex to provide a simpler and more intuitive state management solution. Pinia's design philosophy is simple, easy to learn and use, and supports combination and option APIs. It allows sharing state across components or pages, avoiding many complex concepts in Vuex.
2. Install Pinia
Installing Pinia is very simple and can be done via npm or yarn:
bash copy
npm install pinia --save
or
yarn add pinia
3. Create the Pinia Store
In Pinia, the core of state management is the Store. Store can be understood as an object containing states, getters, and actions. Here is a basic example of creating a Store:
JavaScript Copy
// stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ isLoggedIn: false, user: null }), actions: { login(user) { = true; = user; }, logout() { = false; = null; } }, getters: { isUserLoggedIn: (state) => , currentUser: (state) => } });
4. Register Pinia
Register Pinia and Store in the main app file:
5. Use the Pinia Store in the component
In the Vue component, you can access Pinia's store through useUserStore:
vue copy
<template> <div> <p v-if="">Welcome, {{ }}!</p> <button @click="login">Login</button> <button @click="logout">Logout</button> </div> </template> <script setup> import { useUserStore } from '@/stores/user'; const userStore = useUserStore(); function login() { ({ name: 'John Doe' }); } function logout() { (); }
6. Solution to data preservation after refreshing the page
In web applications, it is usually necessary to deal with data loss after page refresh. To maintain Pinia state after refreshing the page, you can use localStorage or sessionStorage to persist storage state. Pinia provides a plugin pinia-plugin-persistedstate, which can automatically save state to localStorage or sessionStorage to prevent data loss after refreshing the page.
6.1 Install the plug-in
npm install pinia-plugin-persistedstate
6.2 Configuration plug-in
Introduce and register the plugin in src/:
JavaScript Copy
// src/ import { createApp } from 'vue'; import { createPinia } from 'pinia'; import piniaPersist from 'pinia-plugin-persistedstate'; import App from './'; const app = createApp(App); const pinia = createPinia(); (piniaPersist); (pinia); ('#app');
6.3 Configuring Pinia Store Persistence
In your store, you can configure the persist option to specify which states need to be persisted:
// src/stores/ import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ isLoggedIn: false, user: null }), actions: { login(user) { = true; = user; }, logout() { = false; = null; } }, persist: { enabled: true, // Enable persistence strategies: [ { storage: localStorage, // Use localStorage storage paths: ['isLoggedIn', 'user'] // Persist these two fields } ] } });
7. Manual persistence (optional)
If you don't want to use plugins, you can also manually implement data retention for page refresh. Here is a simple example showing how to save state to localStorage and restore state from localStorage when the page loads:
JavaScript Copy
// src/stores/
import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ isLoggedIn: ('isLoggedIn') === 'true', // Get the value from localStorage and convert it user: (('user') || 'null') // Get the value from localStorage }), actions: { login(user) { = true; = user; ('isLoggedIn', 'true'); //Storage to localStorage ('user', (user)); //Storage to localStorage }, logout() { = false; = null; ('isLoggedIn'); // Delete the data in localStorage ('user'); // Delete the data in localStorage } } });
In this way, by manually managing localStorage, you can also implement data after page refresh.
8. Principle of persistent preservation
The principle of persistent saving is to synchronously save it to localStorage or sessionStorage when data is updated in Pinia, and read data from local storage after refreshing. You can choose to write it yourself, but it is not as easy as you imagined to implement it, and of course, it is not that difficult. It is recommended to use plug-ins to achieve persistent storage, which is more convenient and time-saving.
8.1 Using plug-ins
Use the pinia-plugin-persistedstate plugin to automatically save state to localStorage or sessionStorage and automatically read after refresh. The plug-in configuration is very flexible, and it can specify which states need to be persisted and which storage method is used.
8.2 Manual implementation
Manually implementing persistent storage requires the setItem method of localStorage or sessionStorage to be manually called when each state is updated, and the getItem method is called when the page is loaded to restore the state. Although this method is flexible, it has a large amount of code and is prone to errors.
9. Code Example
Here is a complete example showing how to use the pinia-plugin-persistedstate plugin to implement persistence of Pinia state.
9.1 Install the plug-in
npm install pinia-plugin-persistedstate
9.2 Configuration plug-in
Introduce and register the plugin in src/:
JavaScript Copy
// src/ import { createApp } from 'vue'; import { createPinia } from 'pinia'; import piniaPersist from 'pinia-plugin-persistedstate'; import App from './'; const app = createApp(App); const pinia = createPinia(); (piniaPersist); (pinia); ('#app');
9.3 Create Store
Create a Store with user status and enable persistence:
// src/stores/ import { defineStore } from ‘pinia'; export const useUserStore = defineStore(‘user', { state: () => ({ isLoggedIn: false, user: null }), actions: { login(user) { = true; = user; }, logout() { = false; = null; } }, persist: { enabled: true, // Enable persistencestrategies: [ { storage: localStorage, // Use localStorage storagepaths: [‘isLoggedIn', ‘user'] // Persist these two fields} ] } });
9.4 Using Store in Components
Use Store in Vue components and call login and logout methods:
Welcome, {{ }}!
10. Summary
By using the pinia-plugin-persistedstate plug-in, persistent storage of Pinia state can be easily implemented to prevent data loss after page refresh. Although it is flexible to manually implement persistent storage, it has a large amount of code and is prone to errors. In actual development, it is recommended to use plug-ins to simplify the development process and improve development efficiency.
11. Things to note
Storage limit: The storage capacity of localStorage and sessionStorage is limited, usually around 5MB. If the amount of data stored is too large, storage failure may occur.
Security: The data stored in localStorage and sessionStorage is stored in plain text and is easily tampered with by malicious users. If the stored data contains sensitive information, encryption is required.
Compatibility: localStorage and sessionStorage are supported in all modern browsers, but may not be supported in some older browsers. If you need to support older browsers, compatibility is required.
The above is a detailed explanation of how Vue Pinia can refresh and not lose data. For more information about Vue Pinia's refresh and not lose data, please follow my other related articles!