首页 > 解决方案 > 在计算中返回一个 getter 创建一个循环

问题描述

我在计算的内部调用存储中的一个动作来运行它,在我返回一个 getter 之后,这将创建一个循环。

的HTML

{{loadedProjects}}

计算出的

computed: {
    loadedProjects() {
      this.$store.dispatch("getProjects");
      return this.$store.getters.loadedProjects;
    }
  }

店铺

import Vuex from "vuex";
import axios from "axios";

const createStore = () => {
    return new Vuex.Store({
        state: {

            loadedProjects: []
        },
        mutations: {
            setProjects(state, projects) {
                state.loadedProjects = projects
            }

        },
        actions: {
            getProjects(vuexContext) {
                console.log("hello1")
                return axios.get("THE API URL")
                    .then(res => {
                        console.log("hello2")
                        vuexContext.commit("setProjects", res.data);
                    })
                    .catch(e => console.log(e));
            }

        },
        getters: {
              loadedProjects(state) {
                return state.loadedProjects;
              }
        }
    });
};

export default createStore;

我希望调用我的操作来填充我的状态,然后返回我的状态以呈现我的数据。

标签: vue.jsvuex

解决方案


使用在计算属性中进行 API 调用的 store 操作有什么意义……也许您想触发loadedProjects更改?....computed 属性不是异步的,因此无论哪种方式,返回行都将在您获得响应之前执行...您可以尝试vue-async-computed插件,或者created像您所做的那样使用挂钩上的调用更好的方法,你不必使用计算属性,你可以{{ $store.getters.loadedProjects }}在你的模板上使用


推荐阅读