安装依赖
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: {},
})