programing

API에서 ChartJS가 포함된 VueJs 채우기

prostudy 2022. 4. 27. 21:37
반응형

API에서 ChartJS가 포함된 VueJs 채우기

내 차트를 내 API의 데이터로 채우는 방법

<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar } from 'vue-chartjs'
import axios from 'axios'

export default {
data() {
  return {
    dailyLabels: [] ,
    dailyData: []
  }
},
extends: Bar,
mounted() {
  // Overwriting base render method with actual data.
  this.renderChart({
    labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday ', 'Friday', 'Saturday', 'Sunday'],
    datasets: [
      {
        label: 'Daily Students',
        backgroundColor: '#f87979',
        data: [12, 20, 1, 50, 10, 40, 18]
      }
    ]
  })
},
created() {
  axios.get(`https://localhost:44379/api/DailyStudents`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.dailyData = response.data.days
    })
    .catch(e => {
      this.errors.push(e)
    })
}
}
</script>

MY API에서 반환되는 항목:

[
  {"day":"Wednesday","totalStudents":"21"},
  {"day":"Tuesday","totalStudents":"2"},
  {"day":"Thursday","totalStudents":"20"},
  {"day":"Friday","totalStudents":"23"}
]

일수는 내 레이블 및 총 학생 내 데이터여야 함

차트는 물론 학생 수를 일일별로 보여줘야 하지만, 내가 발견한 예들은 조금 혼란스럽다.

사용할 수 있다Array.map필요한 데이터를 추출하기 위해

<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar, mixins } from 'vue-chartjs'
import axios from 'axios'

export default {
  mixins: [mixins.reactiveData],
  data() {
    return {
      chartData: ''
    }
  },
  extends: Bar,
  mounted() {
    this.renderChart(this.chartData)
  },
  created() {
    axios.get(`https://localhost:44379/api/DailyStudents`)
      .then(response => {
        // JSON responses are automatically parsed.
        const responseData = response.data
        this.chartData = {
          labels: responseData.map(item => item.day),
          datasets: [
            label: 'Daily Students',
             backgroundColor: '#f87979',
             data: responseData.map(item => item.totalStudents)
          ]
        }
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}
</script>

사용할 필요가 있다는 점에 유의mixins.reactiveData구성 요소를 데이터 변경 시 대응적으로 만들기 위해

참조URL: https://stackoverflow.com/questions/53938177/vuejs-with-chartjs-populate-from-api

반응형