Allen-1998 / pinia-plugin-persist-uni

Persist pinia state data in uniAppStorage.
https://allen-1998.github.io/pinia-plugin-persist-uni/
MIT License
58 stars 9 forks source link

持久化添加到storage成功,但是在刷新时依然丢失 #19

Open BdQingSan54 opened 3 days ago

BdQingSan54 commented 3 days ago

export function createApp() {

const app = createSSRApp(App); setupPinia(app); return { app, }; }


 - store/index.js

import { createPinia } from 'pinia'; import piniaPersist from 'pinia-plugin-persist-uni';

// 自动注入所有pinia模块 const files = import.meta.glob('./.js', { eager: true }); const modules = {}; Object.keys(files).forEach((key) => { modules[key.replace(/(.\/)([^.]+)./gi, '$2')] = files[key].default; });

export const setupPinia = (app) => { const pinia = createPinia(); pinia.use(piniaPersist);

app.use(pinia); };

export const initPinia = createPinia()

export default (name) => { return modules[name](); };


 - user.js

import { defineStore } from 'pinia'; import { clone, cloneDeep } from 'lodash-es'; import UserApi from '@/api/member/user';

// 默认用户信息 const defaultUserInfo = { avatar: '', // 头像 nickname: '', // 昵称 gender: 0, // 性别 mobile: '', // 手机号 point: 0, // 积分 }

const user = defineStore({ id: 'user', state: () => ({ userInfo: clone(defaultUserInfo), // 用户信息 }),

actions: { // 获取用户信息 async getInfo() { const { code, data } = await UserApi.getUserInfo(); if (code !== 0) { return; } this.userInfo = data; return Promise.resolve(data); } }, persist: { enabled: true, strategies: [ { key: 'user-store', }, ], }, });

export default user;

Allen-1998 commented 1 day ago

store/index.js 中存在两处 createPinia(), 会重复创建 Pinia 实例,这可能是导致回显失败的原因,看你的引用代码中并没有使用 initPinia, 是否应该把它去掉

Allen-1998 commented 1 day ago

或者可以参考我的这个示例项目中的写法