vue3全局状态管理的方案是用pinia,pinia的持久化要怎么实现呢?
方法1 利用插件
安装插件
1
   | yarn add pinia-plugin-persistedstate
   | 
 
在创建pinia实例的时候,注册插件
1 2 3 4 5
   | import { createPinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersistedstate) app.use(pinia)
  | 
 
在store中定义持久化字段
1 2 3 4 5 6 7 8 9 10 11 12 13
   | import { defineStore } from 'pinia'
  export const useAuthStore = defineStore('auth', {   state: () => ({     token: '',     userInfo: null,   }),   persist: {     key: 'auth',      storage: sessionStorage,      paths: ['token'],    }, })
  | 
 
通过以上3步就可以实现pinia持久化了
方法2 手动实现
定义Store时初始化数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | import { defineStore } from 'pinia'
  export const useCartStore = defineStore('cart', {   state: () => ({     items: [],   }),   actions: {          hydrate() {       const savedState = localStorage.getItem('cart')       if (savedState) {         this.$patch(JSON.parse(savedState))       }     },          saveState() {       localStorage.setItem('cart', JSON.stringify(this.$state))     }   } })
  | 
 
在组件中初始化和订阅变化
1 2 3 4 5 6 7 8 9 10
   | import { useCartStore } from '@/stores/cart'
  const cartStore = useCartStore()
  cartStore.hydrate()
 
  cartStore.$subscribe((mutation, state) => {   localStorage.setItem('cart', JSON.stringify(state)) })
  |