大神們好 小弟在實作 vue3 + apexcharts + axios GET Data回array時無法顯示
x軸與y軸資料,但單純顯示array內資料是有的,想請問是哪邊導致資料沒辦法顯示
<template>
<apexchart height="300" type="area" :options="options" :series="series"></apexchart>
{{ info }}
</template>
<script>
import { defineComponent } from 'vue'
import axios from 'axios'
export default defineComponent({
name: 'ApexArea',
data() {
return {
info: [],
options: {
title: {
text: 'ApexArea',
align: 'left'
},
chart: {
height: 300,
type: 'area'
},
markers: {
size: 4,
hover: {
sizeOffset: 6
}
}
},
series: [
{
name: 'test',
data: []
}
]
}
},
created: function () {
this.getData()
},
methods: {
getData() {
// TODO Axios to get data here.
axios
.get('http://my-json-server.typicode.com/apexcharts/apexcharts.js/yearly')
.then(response => {
this.info = response.data
})
.catch(function (error) {
console.log(error)
})
// Format data correctly
const formattedData = this.info.map((i) => {
return {
x: i.x,
y: i.y
}
})
// update the series with axios data
this.series = [
{
name: 'test',
data: formattedData
}
]
}
}
})
</script>
異步問題,你原本的寫法,在axios取得資料之前, Format data correctly 那塊就已經執行了。所以你的 this.series.data 應該是 []
<template>
<apexchart height="300" type="area" :options="options" :series="series"></apexchart>
{{ info }}
</template>
<script>
import { defineComponent } from 'vue'
import axios from 'axios'
export default defineComponent({
name: 'ApexArea',
data() {
return {
info: [],
options: {
title: {
text: 'ApexArea',
align: 'left'
},
chart: {
height: 300,
type: 'area'
},
markers: {
size: 4,
hover: {
sizeOffset: 6
}
}
},
series: [
{
name: 'test',
data: []
}
]
}
},
created: function () {
this.getData()
},
methods: {
// 改成異步函式
async getData() {
// 阻塞到axios取回回應,存到response裡面。錯誤捕捉請自己用try/catch寫。
const response = await axios
.get('http://my-json-server.typicode.com/apexcharts/apexcharts.js/yearly')
this.info = response.data
// Format data correctly
const formattedData = this.info.map((i) => {
return {
x: i.x,
y: i.y
}
})
// update the series with axios data
this.series = [
{
name: 'test',
data: formattedData
}
]
}
}
})
</
改成這樣試試。
要不然你的 Format data correctly 這塊得丟到then裡面。