如何从 API 获取数据以在 Vuejs 中使用 chartjs 显示图表
How to get Data from API to display chart using chartjs in Vuejs
我是 Vuejs 的新手,我想知道如何从我的 API 中获取数据以显示图表。
下面是我的代码,我将数据用作“日期和挑战”并直接向其提供数据,但现在我想调用我的 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/Whosebug/fetchchartdataforvuejs
请有人帮我在我的代码中使用我的 API 来显示图表。
你试过这样的吗?
解决方案 1
添加 async/await
,这样它将等到数据填充到 data
和 challege
。
async mounted () {
let result = await axios.get('https://api.wirespec.dev/wirespec/Whosebug/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, 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>
在其他组件中,导入您的 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 中,从 data
中删除 date
和 challege
因为您将有 props
,最佳实践 props
和 data
不能有相同的 属性 名称。
在导入了chart.vue的其他组件中,照常获取数据即可。
我在项目中使用chartjs时所做的事情,我总是在中添加v-if
,它会让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/Whosebug/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>
我是 Vuejs 的新手,我想知道如何从我的 API 中获取数据以显示图表。
下面是我的代码,我将数据用作“日期和挑战”并直接向其提供数据,但现在我想调用我的 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/Whosebug/fetchchartdataforvuejs
请有人帮我在我的代码中使用我的 API 来显示图表。
你试过这样的吗?
解决方案 1
添加 async/await
,这样它将等到数据填充到 data
和 challege
。
async mounted () {
let result = await axios.get('https://api.wirespec.dev/wirespec/Whosebug/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, 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>
在其他组件中,导入您的 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 中,从 data
中删除 date
和 challege
因为您将有 props
,最佳实践 props
和 data
不能有相同的 属性 名称。
在导入了chart.vue的其他组件中,照常获取数据即可。
我在项目中使用chartjs时所做的事情,我总是在中添加v-if
,它会让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/Whosebug/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>