nuxt3中引入pinia+数据持久化储存(pinia-plugin-persistedstate)

1、按装pinia

yarn add pinia @pinia/nuxt
# 或者使用 npm
npm install pinia @pinia/nuxt

2 、安装pinia-plugin-persistedstate

npm : npm i pinia-plugin-persistedstate
yarn : yarn add pinia-plugin-persistedstate

3、nuxt工程代码中注册插件(/plugis/pinia.ts文件中)

import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.$pinia.use(piniaPluginPersistedstate)
})

4、配置nuxt.config.ts中的modules 

 modules: [
    '@pinia/nuxt'
  ],

5、定义一个store(/store/counter.ts文件中)

import { defineStore } from 'pinia'

interface CounterState {
  times: number
  name: string
}

export const useCounter = defineStore('counter', {
  state: (): CounterState => ({
    times: 5,
    name: 'jjww'
  }),

  actions: {
    increment() {
      this.times++
    }
  },

  persist: process.client && {
    storage: localStorage,
    paths: ['times']
  }
})

注意:persist定义要做判断,因为localStorage是客户端参数,所以需要加process.client

6、在页面只中使用pinia的store




7、测试数据持久化

初始状态times :5

nuxt3中引入pinia+数据持久化储存(pinia-plugin-persistedstate)_第1张图片

点击按钮, times变化后,刷新页面,times依然恢复到最后状态

nuxt3中引入pinia+数据持久化储存(pinia-plugin-persistedstate)_第2张图片

你可能感兴趣的:(前端)