如何使用来自API的数据填充图表?

huangapple go评论46阅读模式
英文:

How to populate a chart with data coming from API?

问题

  1. 如何正确使用API数据填充图表(在我的情况下使用Vuex)?
  2. 如何从API中选择特定的列名并传递给图表?例如,我有20列,只想在图表上显示其中的3列?

我只会回答这两个问题,不会提供其他内容。以下是答案:

  1. 为了正确填充图表,您可以在mounted()生命周期钩子中调用renderChart()方法来渲染图表,确保在获取数据之后再渲染。这是一种常见的方式,如下所示:
mounted() {
  this.loaded = false;
  try {
    this.getAllSalesAction().then(() => {
      this.loaded = true;
      this.renderChart();
    }).catch((error) => {
      console.error(error);
    });
  } catch (e) {
    console.error(e);
  }
}
  1. 要选择特定的列名并将其传递给图表,您可以在获取API数据后,在mounted()生命周期中对数据进行转换。在getAllSalesAction方法中,根据您需要的列名,创建一个新对象,然后将其传递给图表。这是一个示例:
async getAllSalesAction({ commit }) {
  const response = await axios.get(`https://localhost:44327/api/Commission/allData`);
  const data = response.data;

  // 选择需要的列名
  const selectedData = data.map(item => ({
    columnName1: item.columnName1,
    columnName2: item.columnName2,
    columnName3: item.columnName3
  }));

  commit('getAllSales', selectedData);
}

这样,您将只传递所需的列名到图表中。确保在renderChart()之前对数据进行选择和处理。

英文:

I use vue-chart.js along with Vue2 to create a chart. I have a problem with passing API data to a chart. I use Vuex store where I fetch data from API. There's a poor example on vue-chartjs.org showing how to handle an API. I also checked SO looking for an answer but in most cases renderChart() placed in mounted() is used, don't know if it's some workaround or proper way of dealing with this problem. I know that I need to pass Object instead of Array. I pass state directly to data , here :data="allSales". This is my problematic code which throws errors:

> Invalid prop: type check failed for prop "data". Expected Object, got Array

> Error in mounted hook: "TypeError: Cannot read properties of undefined (reading 'map')"

<template>
  <v-container>
    <v-row>
      <v-col cols="6">
        <Bar v-if="loaded"
          id="my-chart-id"
          :options="chartOptions"
          :data="allSales"/>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import { Bar } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

  export default {

    components: {
      Bar
    },

    data() {
      return {
      chartOptions: {
        responsive: true
      },
      loaded: false
      }
    },

    computed: {
      ...mapState('custom', ['allSales'])
    },

    methods: {
      ...mapActions('custom', ['getAllSalesAction']),
    },

    mounted() {   
      
      this.loaded = false
      try {
        this.getAllSalesAction()
        this.loaded = true
      } catch (e) {
        console.error(e)
      }
    },

  }
</script>

EDIT: I add my Vuex store:

import axios from "axios";


const state = {
    allSales: [],
};

const mutations = {
    getAllSales: (state, all) => state.allSales = all, 

};

const actions = {
    async getAllSalesAction({commit})
    {       
        const response = await axios.get(`https://localhost:44327/api/Commission/allData`)
        commit('getAllSales', response.data)
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};

Basically I have 2 questions:

  1. How properly populate chart with API data (using Vuex in my case)?
  2. How can I choose specific column names from API and pass to a chart? Say I have 20 columns and just wanted to show 3 of them on a chart?

答案1

得分: 2

Read carefully the documentation and notice how the data prop of the Bar component is of type Object while you are feeding it with Array.

Follow the example from the documentation and use a Vuex getter instead of directly reading the state in order to generate the right data format:

const getters = {
  getAllSales(state)
  {
    return {
      labels: ['January', 'February', 'March'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#F87979',
          data: state.allSales,
        }
      ]
    };
  },
};

<details>
<summary>英文:</summary>

Read carefully the [documentation](https://vue-chartjs.org/guide/#chart-with-local-data) and notice how the `data` prop of the `Bar` component is of type `Object` while you are feeding it with Array.

Follow the example from the documentation and use a Vuex getter instead of directly reading the state in order to generate the right data format:
```javascript
const getters = {
  getAllSales(state)
  {
    return {
      labels: [ &#39;January&#39;, &#39;February&#39;, &#39;March&#39;],
      datasets: [
        {
          label: &#39;Data One&#39;,
          backgroundColor: &#39;#F87979&#39;,
          data: state.allSales,
        }
      ]
    };
  },
};

</details>



huangapple
  • 本文由 发表于 2023年4月7日 00:14:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定