问题描述
我是 Vuejs 的新手,我想知道如何从我的 API 中获取数据以显示图表。
以下是我的代码,其中我将数据用作“日期和挑战”并直接向其提供数据,但现在我想调用我的 API 并将其中的数据提供给“日期和挑战”。
><template>
<canvas id="mychart" width="550" height="300"></canvas>
</template>
<script>
export default {
name: 'Chart',data: () => ({
date: [
1600934100.0,1602009600.0,1602747060.0,1603050158.390939,1603305573.992575
],challenge: [
9.0,9.5,2.5,11.52,12.4
]
}),mounted () {
// eslint-disable-next-line no-unused-vars
const data = this.date.map((date,index) => ({
x: new Date(date * 1000),y: this.challenge[index]
}))
const ctx = document.getElementById('mychart').getContext('2d')
// eslint-disable-next-line no-undef,no-unused-vars
const Chart_2 = new Chart(ctx,{
type: 'line',data: {
datasets: [
{
data,label: 'Chart from API ',borderColor: '#7367F0'
}
]
},options: {
scales: {
xAxes: [
{
type: 'time',time: {
unit: 'month',displayFormats: {
month: 'MMM YYYY'
}
}
}
],yAxes: [
{
ticks: {
// eslint-disable-next-line no-unused-vars
callback (value,index,values) {
return `${value }%`
}
}
}
]
}
}
})
}
}
</script>
我知道要获取 API 我们使用 'axios' 或 'fetch' ,所以每当我获取 API 并执行 console.log(response.data) 时,我都会在浏览器的控制台中获取我的数据,但我不会知道映射它并使用这些数据来提供“日期和挑战”以显示图表。
这是我的 API:
其中包含数据的我的 API:https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs
解决方法
你试过这样的吗?
解决方案 1
添加 async/await
以便等待数据填充到 data
和 challege
。
async mounted () {
let result = await axios.get('https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs')
this.date = result.data.date
this.challenge = result.data.challenge
// eslint-disable-next-line no-unused-vars
const data = this.date.map((date,index) => ({
x: new Date(date * 1000),y: this.challenge[index]
}))
const ctx = document.getElementById('mychart').getContext('2d')
// eslint-disable-next-line no-undef,no-unused-vars
const Chart_2 = new Chart(ctx,{
type: 'line',data: {
datasets: [
{
data,label: 'Chart from API ',borderColor: '#7367F0'
}
]
},options: {
scales: {
xAxes: [
{
type: 'time',time: {
unit: 'month',displayFormats: {
month: 'MMM YYYY'
}
}
}
],yAxes: [
{
ticks: {
// eslint-disable-next-line no-unused-vars
callback (value,index,values) {
return `${value }%`
}
}
}
]
}
}
})
}
或者换一种方式,你可以从其他组件的 API 中获取数据,然后将 date
和 challege
作为 props 发送给这个组件。
解决方案 2
我假设您有图表组件 chart.vue
chart.vue
<template>
<canvas id="mychart" width="550" height="300"></canvas>
</template>
<script>
export default {
name: 'Chart',props: ['date','challenge],data: () => ({
}),mounted () {
// eslint-disable-next-line no-unused-vars
const data = this.date.map((date,values) {
return `${value }%`
}
}
}
]
}
}
})
}
}
</script>
并在其他组件中,导入您的 chart.vue
<template>
<div>
<Chart v-if="!isLoading" :date="date" :challenge="challenge" />
</div>
</template>
<script type="text/javascript">
import Chart from 'PATH TO chart.vue'
export default {
components: {
Chart
},data () => ({
date: [],challenge: [],isLoading: false
}),methods: {
async getData () {
this.isLoading = true
let result = await axios.get(API URL)
this.date = result.data.date
this.challenge = result.data.challenge
this.isLoading = false
}
},mounted () {
this.getData()
}
}
</script>
在 chart.vue 中,从 date
中删除 challege
和 data
,因为您将拥有 props
,以获得最佳实践 {{1} }} 和 props
不能具有相同的属性名称。
在导入 chart.vue 的其他组件中,只需像往常一样获取数据。
我在我的项目中使用chartjs时所做的事情,我总是在其中添加data
,它会让axios先获取数据,然后重新安装图表组件。因为我猜 chartjs 不会对 vuejs 数据变化做出反应,所以需要先更新数据,然后再重新挂载。
终于,我得到了答案万岁!
我正在分享,我是如何做到的,即使您也可以这样做,以便使用您的 API 数据可视化图表。
<template>
<div class="chart-container" style="position: relative; height: 25vh; width:100%;">
<canvas id="DisplayChart" ></canvas>
</div>
</template>
<script>
import moment from 'moment'
export default {
name: 'Chart_from_API',data () {
return {
myChart: []
}
},async mounted () {
await this.$http.get('https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs') //Your API has to be given here
.then((response) => {
const result = response.data
const ctx = document.getElementById('DisplayChart').getContext('2d')
const Chart_data = []
for (let i = 0; i < result.date.length; i++) {
Chart_data.push({
x_axis: moment(result.date[i],'X').toDate(),//To Convert Unix Timestamp into Date
y_axis: result.challenge[i]
})
}
// eslint-disable-next-line init-declarations,prefer-const
let myChart
if (myChart !== undefined) {
myChart.destroy()
}
// eslint-disable-next-line no-undef
myChart = new Chart(ctx,{
type: 'line',data: {
datasets: [
{
label: 'Chart_from_API',data: Chart_data,borderColor: '#EA5455',lineTension: 0
}
]
},options: {
lineTension: 0,maintainAspectRatio: false,legend: {
display: false
},scales: {
yAxes: [
{
scaleLabel: {
display: false
},ticks: {
beginAtZero: true,// eslint-disable-next-line no-unused-vars
callback (value) {
return `${value }k` // y-axis value will append k to it
}
}
}
],xAxes: [
{
type: 'time',time: {
unit: 'month'
},scaleLabel: {
display: true,labelString: ''
}
}
]
}
}
})
})
.catch((error) => {
console.log(error)
})
}
}
</script>