【uniapp】状态存储Pinia的使用,以及它的数据持久化

1、下载安装pinia,引入pinia

javascript 复制代码
//stores->index.ts
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate' //持久化插件

// 创建 pinia 实例
const pinia = createPinia()
// 使用持久化存储插件
pinia.use(persist)

// 默认导出,给 main.ts 使用
export default pinia

// 模块统一导出
export * from './modules/member'
// export * from './modules/xxxxx' //如果有多个模块,依次导出即可
// export * from './modules/xxxxx' //如果有多个模块,依次导出即可

并且在main.ts中引入:

javascript 复制代码
import { createSSRApp } from 'vue'
import pinia from './stores'

import App from './App.vue'
export function createApp() {
  const app = createSSRApp(App)

  app.use(pinia)
  return {
    app,
  }
}

2、定义pinia,并持久化

javascript 复制代码
//stores->modules->member.ts
import { defineStore } from 'pinia'

// 定义 Store
export const useMemberStore = defineStore('member', {
  state: () => ({
    profile: null,
  }),
  actions: {
    setProfile(obj: any) {
      this.profile = obj
    },
    clearProfile() {
      this.profile = null
    },
  },
  //pinia数据持久化
  persist: {
    storage: {
      getItem(key) {
        return uni.getStorageSync(key)
      },
      setItem(key, value) {
        return uni.setStorageSync(key, value)
      },
    },
  },
})
相关推荐
艾小逗1 小时前
vue3中的effectScope有什么作用,如何使用?如何自动清理
前端·javascript·vue.js
小小小小宇4 小时前
手写 zustand
前端
Hamm4 小时前
用装饰器和ElementPlus,我们在NPM发布了这个好用的表格组件包
前端·vue.js·typescript
明似水5 小时前
Flutter 弹窗队列管理:支持优先级的线程安全通用弹窗队列系统
javascript·安全·flutter
小小小小宇5 小时前
前端国际化看这一篇就够了
前端
大G哥5 小时前
PHP标签+注释+html混写+变量
android·开发语言·前端·html·php
whoarethenext5 小时前
html初识
前端·html
小小小小宇5 小时前
一个功能相对完善的前端 Emoji
前端
m0_627827525 小时前
vue中 vue.config.js反向代理
前端
Java&Develop5 小时前
onloyoffice历史版本功能实现,版本恢复功能,编辑器功能实现 springboot+vue2
前端·spring boot·编辑器