Pinia 版本:确保你使用的是 Pinia v3 或更高版本,因为 pinia-plugin-persistedstate
是官方为 Pinia v3 维护的插件
该插件的官方源码和文档位于 GitHub: https://github.com/prazdevs/pinia-plugin-persistedstate
1. 安装插件(bash)
npm install pinia-plugin-persistedstate
# 或
yarn add pinia-plugin-persistedstate
2. 配置 Pinia 和插件
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate) // 启用插件
const app = createApp(App)
app.use(pinia)
app.mount('#app')
3. 在 Store 中启用持久化
(1) 基本用法(默认 localStorage)
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
persist: true, // 启用持久化
})
(2) 自定义存储 key 和方式(如 sessionStorage)
4. 支持的配置选项
选项 | 类型 | 默认值 | 说明 |
---|---|---|---|
key | string | store 的 id | 存储的 key 名称 |
storage | Storage | localStorage | 存储引擎(localStorage 或 sessionStorage ) |
paths | string[] | undefined | 指定需要持久化的 state 字段 |
beforeRestore | Function | undefined | 恢复 state 前的钩子 |
afterRestore | Function | undefined | 恢复 state 后的钩子 |
5. 存储类型
localStorage
:浏览器关闭后仍然有效,适用于长期存储数据。sessionStorage
:浏览器会话结束时会被清除,适用于临时数据。
6. 注意事项
- Pinia 版本:仅支持 Pinia v3+(官方维护插件)。
- SSR 兼容性:
localStorage
在服务端不可用,需额外处理(如 Nuxt 项目)。 - 安全性:避免存储敏感信息(如 token、密码)。
7. 清除持久化数据
在 Store 中添加 clearPersistence 方法
// stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: '',
token: '',
}),
persist: {
key: 'user-store', // 自定义存储 key
storage: localStorage, // 使用 localStorage
},
actions: {
// 封装清除持久化数据的方法
clearPersistence() {
localStorage.removeItem('user-store') // 删除对应的持久化数据
// 也可以重置 state(可选)
this.$reset() // Pinia 提供的 $reset 方法,重置 state 为初始值
},
},
})
在组件或逻辑中调用:
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
userStore.clearPersistence() // 清除持久化数据并重置 state
8.在用户登出时清除持久化数据(完整示例)
// stores/auth.js
import { defineStore } from 'pinia'
export const useAuthStore = defineStore('auth', {
state: () => ({
token: '',
user: null,
}),
persist: {
key: 'auth-store',
storage: localStorage,
},
actions: {
logout() {
// 清除持久化数据
localStorage.removeItem('auth-store')
// 或使用 this.$reset() 重置 state(可选)
this.$reset()
// 其他登出逻辑(如跳转登录页)
window.location.href = '/login'
},
},
})
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore()
authStore.logout() // 登出并清除持久化数据
方法 | 适用场景 | 示例 |
---|---|---|
浏览器开发者工具 | 开发调试 | 手动删除 localStorage / sessionStorage 中的 key |
localStorage.removeItem(key) | 编程式清除 | localStorage.removeItem('user-store') |
store.clearPersistence() | 封装清除逻辑 | 在 Store 中定义方法,方便调用 |
this.$reset() | 重置 state | 结合 removeItem 使用,恢复初始状态 |