pinia持久化存储

This commit is contained in:
Fsd0511 2025-09-01 22:43:08 +08:00
parent 18d6627f41
commit 58da6a52b9
2 changed files with 26 additions and 23 deletions

12
main.js
View File

@ -5,13 +5,14 @@ import store from './store' // Vuex store如果还在用
import { install } from './plugins' // 自定义插件 import { install } from './plugins' // 自定义插件
import './permission' // 路由权限 import './permission' // 路由权限
import { useDict } from '@/utils/dict' import { useDict } from '@/utils/dict'
import { createPinia } from 'pinia' // import { createPinia } from 'pinia'
import * as Pinia from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
export function createApp() { export function createApp() {
const app = createSSRApp(App) const app = createSSRApp(App)
const pinia = createPinia() // const pinia = createPinia()
const pinia = Pinia.createPinia()
// ✅ 安全注册持久化插件 // ✅ 安全注册持久化插件
if (piniaPluginPersistedstate) { if (piniaPluginPersistedstate) {
pinia.use(piniaPluginPersistedstate) pinia.use(piniaPluginPersistedstate)
@ -20,7 +21,7 @@ export function createApp() {
} }
app.use(pinia) app.use(pinia)
app.use(store) // 如果你还在用 Vuex否则可删除 // app.use(store) // 如果你还在用 Vuex否则可删除
// 挂载全局方法 // 挂载全局方法
app.config.globalProperties.useDict = useDict app.config.globalProperties.useDict = useDict
@ -29,6 +30,7 @@ export function createApp() {
install(app) install(app)
return { return {
app app,
Pinia
} }
} }

View File

@ -24,22 +24,23 @@ export const useOrderManagerStore = defineStore('orderManager', () => {
clearOrders clearOrders
}; };
}, { }, {
persist: { // persist: {
storage: { // storage: {
// 读取:从 uni.storage 获取 // // 读取:从 uni.storage 获取
getItem(key) { // getItem(key) {
const value = uni.getStorageSync(key); // const value = uni.getStorageSync(key);
// 如果有值,解析 JSON否则返回 nullPinia 会处理默认值) // // 如果有值,解析 JSON否则返回 nullPinia 会处理默认值)
return value ? JSON.parse(value) : null; // return value ? JSON.parse(value) : null;
}, // },
// 写入:保存到 uni.storage // // 写入:保存到 uni.storage
setItem(key, value) { // setItem(key, value) {
uni.setStorageSync(key, JSON.stringify(value)); // uni.setStorageSync(key, JSON.stringify(value));
}, // },
// 可选:删除(一般不需要手动调用) // // 可选:删除(一般不需要手动调用)
removeItem(key) { // removeItem(key) {
uni.removeStorageSync(key); // uni.removeStorageSync(key);
} // }
} // }
} // }
persist: true
}); });