Vuex 4,组件中的状态为空

Vuex 4, State is empty in component

我正在尝试使用 this.$store.state.subjects 在我的主组件中访问主题存储状态,但它显示为一个空数组。使用 console.log 我唯一能看到 state.subjects 填充的地方是它是否在突变函数中。 在其他任何地方 console.log 都是空的。在我看来,状态并没有从突变中持续存在,但我不确定为什么。

我已经尝试了很多 Whosebug 的答案,但是,没有一个能解决问题,或者我不知道我在 post 中阅读的内容。我还保留了我的代码块中的代码,以使其 post 更具可读性,例如导入或模板。

商店index.js

export default createStore({
    state: {
        subjects: [],
    },
    actions: {
        getSubjects({ commit }) {
            // Manages subjects, allow for display in column or Calendar view
            axiosMain({
                method: "get",
                url: "/study/",
                withCredentials: true,
            })
                .then((response) => {
                    commit("setSubjects", response.data);
                })
        },
    },
    mutations: {
        setSubjects(state, subjectsToSet) {
            state.subjects = subjectsToSet;
            console.log(state.subjects) # Is a populated array
        }
    }
});

Main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import VueGtag from "vue-gtag-next";
import store from "./store";
import "./assets/main.css";

createApp(App)
    .use(router)
    .use(store)
    .use(VueGtag, {
        property: {
            id: "G-E4DPXQ96HB",
        },
    })
    .mount("#app");

Home.vue

<template>
</template>

<script>
export default {
    name: "Home",
    data() {
        return {
            subjects: [],
        };
    },
    mounted() {
        this.callStoreSubjectAction();
        this.setSubjectsToStoreSubject();
    },
    methods: {
        callStoreSubjectAction() {
            this.$store.dispatch("getSubjects");
        },
        setSubjectsToStoreSubject() {
            this.subjects = this.$store.state.subjects;
            console.log(this.$store.state.subjects); # Is an empty array
        },
    },
};
</script>

在组件中,您将在 axios 调用完成之前复制 this.$store.state.subjects 的值。等待承诺先解决。为此,您需要先 return 行动中的承诺:

getSubjects({ commit }) {
  return axiosMain({   // returning the promise
    ... 
  }
}

等待承诺:

mounted() {
  this.$store.dispatch("getSubjects").then(r => {
    this.subjects = this.$store.state.subjects;
    console.log(this.$store.state.subjects);
  });
},

比这更好的方法是从组件数据中删除 subjects 并使用计算代替与 Vuex 状态同步:

import { mapState } from 'vuex';
computed: {
  ...mapState(['subjects'])  // creates a computed `this.subjects`
}

那么您只需分派操作,组件将处理其余部分:

mounted() {
  this.$store.dispatch("getSubjects");
}