侧边栏壁纸
博主头像
龍啓博主等级

行动起来,活在当下

  • 累计撰写 23 篇文章
  • 累计创建 23 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

uniapp中使用pinia,并做数据持久化

龍啓
2023-09-25 / 0 评论 / 0 点赞 / 39 阅读 / 1433 字

安装依赖

npm i pinia pinia-plugin-persistedstate @nuxt/devalue -S

创建插件

创建store文件夹,创建持久化插件store/plugins.ts

// store/plugins.ts
import { App } from 'vue'
import { createPinia } from 'pinia'
import devalue from '@nuxt/devalue'
import { createPersistedState } from 'pinia-plugin-persistedstate'

export const pinia = createPinia()

export const painaInstall = (app: App) => {
  pinia.use(
    createPersistedState({
      storage: {
        getItem(key: string): string | null {
          return uni.getStorageSync(key)
        },
        setItem(key: string, value: string) {
          uni.setStorageSync(key, value)
        },
      },
    }),
  )
  app.use(pinia)

  devalue(pinia.state.value)
}

使用

mian.ts中注册插件

import { createSSRApp } from 'vue'
import App from './App.vue'
import { painaInstall } from '@/store/plugins'

export function createApp() {
  const app = createSSRApp(App)
  app.use(painaInstall)
  return {
    app,
  }
}

创建 store/index.ts

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  persist: true,
  state: () => ({}),
  actions: {},
})
0

评论区