【问题标题】:Vuex 4, State is empty in componentVuex 4,组件中的状态为空
【发布时间】:2021-05-12 21:58:06
【问题描述】:

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

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

存储 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");

首页.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>

【问题讨论】:

    标签: javascript vue.js vue-component vuex vuejs3


    【解决方案1】:

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

    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");
    }
    

    【讨论】:

    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2019-10-15
    • 2020-06-08
    • 2020-10-22
    相关资源
    最近更新 更多