vue3 + pinia 实现持久化存储

659 阅读1分钟

vue3 + pinia + pinia-plugin-persist

安装插件

yarn add pinia pinia-plugin-persist

main.js中使用

import { createApp } from 'vue'
import { createPinia } from 'pinia
import piniaPluginPersist from 'pinia-plugin-persist'

import App from './App.vue'

const app = createApp(App)

app.use(createPinia().use(piniaPluginPersist))

app.mount('#app')

stores/count.ts

import { defineStore } from 'pinia'

export default defineStore({
  key: 'count',
  state: () => {
    count: 0
  },
  getters: {
    getCount: (state) => state.count
  },
  actions: {
    increment() {
      this.count++
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'count',
        storage: localStorage 
      }
    ]
  }
})

\