use*_*642 7 javascript arrays chart.js asp.net-core-webapi vuejs2
如何使用 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>
Run Code Online (Sandbox Code Playgroud)
我的 Api 返回这个:
Run Code Online (Sandbox Code Playgroud)[ {"day":"Wednesday","totalStudents":"21"}, {"day":"Tuesday","totalStudents":"2"}, {"day":"Thursday","totalStudents":"20"}, {"day":"Friday","totalStudents":"23"} ]
天数应该是我的标签,totalStudents 应该是我的数据
图表当然应该显示每天的学生人数,但我发现的例子有点令人困惑。
您可以使用它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>
Run Code Online (Sandbox Code Playgroud)
请注意,您需要使用mixins.reactiveData使组件对数据更改做出反应。
| 归档时间: |
|
| 查看次数: |
3770 次 |
| 最近记录: |