使用 Vuex 和 vue google 图表操作数据

Manipulating data using Vuex and vue google chart

我想从商店获取数据并进行一些操作,然后将其传递给模板中的 vue-google-chart,这是我的实现

export default {
  name: "Chart1",
  components: {
    GChart, // vue google chart component
  },
  data() {
    return {
      data: null,
      totalGeneral: 0,
      totalHomme: 0,
      totalFemme: 0,
      dataHomme: null,
      dataFemme: null,
      filieres: null,
      chartData: [],
      chartOptions: {
        chart: {
          title: "STUDENTS BY ROUTE INITIAL TRAINING",
        },
        is3D: true,
      },
    };
  },
  created() {
    this.$store.dispatch("setFiData"); // it calls the API
  },
mounted() {
    this.getData();
  },

methods: {
    getData() {
      this.data = this.$store.getters.fiData;
      this.chartData = [];
      this.dataFemme = [];
      this.dataHomme = [];
      this.filieres = [];
      if (this.data.length) {
        for (let i = 0; i < this.data.length; i++) {
          this.chartData.push([this.data[i].filiere, this.data[i].total]);
          this.dataHomme.push(this.data[i].homme);
          this.dataFemme.push(this.data[i].femme);
          this.filieres.push(this.data[i].filiere);
          this.totalHomme += this.data[i].homme;
          this.totalFemme += this.data[i].femme;
        }
        this.totalGeneral = this.totalHomme + this.totalFemme;
      } else {
        console.log("NO DATA");
      }
    },
},
},

它只是一直在控制台中给我消息 NO DATA,我不知道为什么,有没有更好的方法来解决这个问题?

您需要检查您的 this.$store.dispatch("setFiData") 是否正常工作并将 fiData 分配到您的商店中。

我想这个 api 调用是一个异步函数,所以我认为在您的情况下最好的方法是这种方式。如果你也发布你的 vuex store 就更好了。

export default {
  name: "Chart1",
  components: {
    GChart, // vue google chart component
  },
  data() {
    return {
      data: null,
      totalGeneral: 0,
      totalHomme: 0,
      totalFemme: 0,
      dataHomme: null,
      dataFemme: null,
      filieres: null,
      chartData: [],
      chartOptions: {
        chart: {
          title: "STUDENTS BY ROUTE INITIAL TRAINING",
        },
        is3D: true,
      },
    };
  },
  
 mounted() {
   this.$store.dispatch("setFiData") // it calls the API
   .then(()=> {
     //Just run getData() when your api request is finished
      this.getData();
   })
  },

methods: {
    getData() {
      this.data = this.$store.getters.fiData;
      this.chartData = [];
      this.dataFemme = [];
      this.dataHomme = [];
      this.filieres = [];
      if (this.data.length) {
        for (let i = 0; i < this.data.length; i++) {
          this.chartData.push([this.data[i].filiere, this.data[i].total]);
          this.dataHomme.push(this.data[i].homme);
          this.dataFemme.push(this.data[i].femme);
          this.filieres.push(this.data[i].filiere);
          this.totalHomme += this.data[i].homme;
          this.totalFemme += this.data[i].femme;
        }
        this.totalGeneral = this.totalHomme + this.totalFemme;
      } else {
        console.log("NO DATA");
      }
    },
},
},