반응형
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
반응형
'programing' 카테고리의 다른 글
vuejs - 구성 요소 간에 웹 사이트 연결 공유 (0) | 2022.04.27 |
---|---|
시간에 따라 여러 VueJS, @vue/cli 종속 애플리케이션을 유지 관리하는 규정된 방법은 무엇인가? (0) | 2022.04.27 |
GCC와 g+++는 어떻게 포장되는가? (0) | 2022.04.27 |
마우스 오른쪽 버튼을 클릭하고 '새로 만들기'를 선택하면 IntelliJ가 '클래스'를 표시하지 않음 (0) | 2022.04.27 |
Vue: 루트 요소 컨텐츠 및 컨텐츠 배포 슬롯 (0) | 2022.04.27 |