求助:关于Pinia

有如下代码:
声明了一个app store

import { getAppAll } from '@/api/app';
import { defineStore } from 'pinia';
import { IAppInfo } from '@/utils/types';
import { store } from '@/store';

export const useAppStore = defineStore('app', {
    state: () => ({
        appList: [],
    }),
    getters: {
        appList: (state) => {
            console.log('getter', state.appList);
            return state.appList;
        },
    },
    actions: {
        async fetchAppList() {
            const resp = await getAppAll();
            const { data } = resp;
            const result = data as Array<IAppInfo>;
            this.$patch((state) => {
                state.appList = result;
            });
        },
    },
});

export function getAppStore() {
    return useAppStore(store);
}

为什么我在其它 组件中获取不到appList的值呢?一直是undefind
其它 组件调用的代码:

import { getAppStore } from '@/store/modules/app';
const appStore = getAppStore();
const { appList } = appStore;
console.log('appList', appList); === undefind
const apps = ref(appList);
if (helper.len(apps.value) === 0) {
    await appStore.fetchAppList();
    apps.value = appStore.appList;
    console.log('apps.value', appStore.appList); === undefind
}
阅读 1.4k
1 个回答

你这个上下文有点少。

你先检查几个点:

  • state 和 getters 里都有一个 appList
  • actions 里先不要使用 $patch,先直接 this.appList = xxx 赋值
  • 是否在 createPinia 和 app.use 之后再使用 store
  • 不要使用解构的方式去读取 store 里的属性

排除上述因素,先让代码尽可能简单,看看问题是否还能复现。

推荐问题