Pinia 作為 Vue 官方推薦的狀態管理庫,其插件機制能有效擴展核心功能,覆蓋 數據持久化、性能優化、開發調試、類型安全 等常見需求。
一、數據持久化插件:pinia-plugin-persistedstate
痛點: 頁面刷新後狀態丟失
npm install pinia-plugin-persistedstate
// main.ts
import { createPinia } from'pinia'
import piniaPluginPersistedstate from'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
// store 配置
exportconst useUserStore = defineStore('user', {
state: () => ({ token: '' }),
persist: {
storage: sessionStorage, // 指定存儲方式
paths: ['token'] // 選擇持久化字段
}
})
適用場景:
- 保持用戶登錄狀態
- 記住表格篩選條件
- 保存用戶主題偏好
二、狀態重置插件:pinia-plugin-reset
痛點: 手動重置複雜狀態容易遺漏
import { createReset } from 'pinia-plugin-reset'
// 初始化
pinia.use(createReset())
// 使用示例
const store = useUserStore()
store.$reset() // 一鍵重置到初始狀態
**適用場景:
- 用戶退出登錄時清理數據
- 表單提交後重置
- 測試用例的初始狀態設置
三、防抖操作插件:@pinia/plugin-debounce
顧名思義,防抖觸發 pinia 更新,減少更新頻率
import { debounce } from 'ts-debounce'
import { PiniaDebounce } from '@pinia/plugin-debounce'
// Pass the plugin to your application's pinia plugin
pinia.use(PiniaDebounce(debounce))
defineStore(
'id',
() => {
// ...the store
return { someSearch }
},
{
debounce: {
// 防抖
someSearch: 300,
},
}
)
四、映射操作插件:pinia-orm
通過映射關係來操作 pinia
import { createPinia } from 'pinia'
import { createORM } from 'pinia-orm'
const pinia = createPinia().use(createORM())
// User Model
import { Model } from'pinia-orm'
exportdefaultclass User extends Model {
// entity is a required property for all models.
static entity = 'users'
// List of all fields (schema) of the post model. `this.string()` declares
// a string field type with a default value as the first argument.
// `this.uid()` declares a unique id if none provided.
static fields () {
return {
id: this.uid(),
name: this.string(''),
email: this.string('')
}
}
// For typescript support of the field include also the next lines
declare id: string
declare name: string
declare email: string
}
五、撤銷/重置插件:pinia-undo
pnpm add pinia pinia-undo
import { PiniaUndo } from 'pinia-undo'
const pinia = createPinia()
pinia.use(PiniaUndo)
const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 10,
}),
actions: {
increment() {
this.count++
},
},
})
const counterStore = useCounterStore()
// undo/redo have no effect if we're at the
// beginning/end of the stack
counterStore.undo() // { count: 10 }
counterStore.redo() // { count: 10 }
counterStore.increment() // { count: 11 }
counterStore.increment() // { count: 12 }
counterStore.undo() // { count: 11 }
counterStore.undo() // { count: 10 }
counterStore.undo() // { count: 10 }
counterStore.redo() // { count: 11 }
六、SSR 支持:@pinia/nuxt
npm install @pinia/nuxt
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@pinia/nuxt']
})
// 自動處理:
// - 服務端數據預取
// - 客戶端狀態同步
// - 避免 hydration 錯誤
七、開發調試插件:vue-devtools 增強
內置支持: 通過瀏覽器插件直接查看
調試技巧:
- 時間旅行調試(狀態回滾)
- 直接修改 store 狀態
- 跟蹤狀態變更來源