Open BdQingSan54 opened 3 days ago
import App from './App'; import { createSSRApp } from 'vue'; import { setupPinia } from './store';
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;
store/index.js 中存在两处 createPinia(), 会重复创建 Pinia 实例,这可能是导致回显失败的原因,看你的引用代码中并没有使用 initPinia, 是否应该把它去掉
store/index.js
createPinia()
或者可以参考我的这个示例项目中的写法
export function createApp() {
const app = createSSRApp(App); setupPinia(app); return { app, }; }
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](); };
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;