最近用vue和echars做了兩個小頁面,遇到一個問題是,在mounted發送請求,和初始化echars圖,發現資料出不來,現在記錄一下解決方法。
解決:在資料請求的時候,生命周期是不會等待你完成請求在繼續走mounted,所有你在mounted初始化echarts的時候,請求可能沒完成,是以說拿不到資料顯示,你可以直接再mounted請求資料,在請求成功回調裡面進行echarts初始化
this.$post('/adminOutAccess/',this.department,this.months).then(response=>{
console.log(response.name)
console.log(response.coverage)
console.log(response.duration)
this.staff = response.name
this.coverage = response.coverage
this.duration = response.duration
this.getData()
})
getData(){
const that = this
const option = {
title:{
text:this.department+" "+this.month+" 月走訪資訊"
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {
color: '#999'
}
}
},
toolbox: {
feature: {
dataView: {show: true, readOnly: false},
magicType: {show: true, type: ['line', 'bar']},
restore: {show: true},
saveAsImage: {show: true}
}
},
legend: {
data: ['走訪時長', '走訪覆寫率']
},
xAxis: [
{
type: 'category',
data: that.staff,
axisPointer: {
type: 'shadow'
}
}
],
yAxis: [
{
type: 'value',
name: '走訪時長',
min: 0,
max: 100,
interval: 10,
axisLabel: {
formatter: '{value} h'
}
},
{
type: 'value',
name: '走訪覆寫率',
min: 0,
max: 100,
interval: 10,
axisLabel: {
formatter: '{value} %'
}
}
],
series: [
{
name: '走訪時長',
type: 'bar',
data: [41.16, 42.20, 9.03, 5.72, 59.63, 31.62, 25.04, 21.83, 49.45, 30.18, 13.59, 23.32, 79.81, 93.15, 38.19, 50.25, 55.52, 0.00, 46.25,
]
// data: this.duration
},
{
name: '走訪覆寫率',
type: 'line',
yAxisIndex: 1,
// data: this.coverage,
data: [100.00,
100.00,
100.00,
38.89,
98.63,
98.33,
67.42,
65.26,
100.00,
80.77,
100.00,
100.00,
99.16,
87.39,
84.81,
100.00,
100.00,
0.00,
100.00,
]
}
]
};
this.chart1 = echarts.init(document.getElementById('chart1'))
this.chart1.setOption(option)
// this.chart1.showLoading();
}