最近做echarts图表时,因为涉及到使用开关变量控制不同图表的显示隐藏,用 v-if 时会出现没有获取到dom结构而报错,所以改用 v-show,但是 v-show 本身是结构已经存在,当数据发生变化时,结构并未重新渲染,所以会出现 echarts 图表未获取到最外层大盒子的宽度而显示一半的情况,就像下图:
百度了各种资料结果都以失败告终,最后使用一下定时器就好了,只需要设置延迟一秒,图表就可以正常显示:为你奉上以下代码参考:
// 分公司营业额图表
search1(row) {
if (row == "趋势分析(月)") {
this.chartflag1 = true
this.tableList = false;
this.chartflag2 = false;
this.monthflag = false;
this.loading1 = true;
// 月折线图掉接口
this.$fetchs(
"/pcadmin/statistics/child/line/chart/month"
).then(res => {
if (res.success == true) {
var result = res.data;
var series1 = [];
var company = [];
for (var i = 0; i < result.length; i++) {
company.push(result[i].company_name);
var data = {
}
for (let key in result[i].data) {
data[key * 1] = result[i].data[key]
}
var datas = []
for (let key in data) {
datas.push(data[key] == '' ? 0 : data[key])
}
series1.push({
name: result[i].company_name,
type: 'line',
stack: '总量',
data: datas
});
}
// 延迟一秒渲染echarts
var that = this
setTimeout(function () {
that.myChart1 = that.$echarts.init(
document.getElementById("myChart1"),
"chalk"
);
// 绘制图表
that.myChart1.setOption({
tooltip: {
trigger: 'axis'
},
legend: {
data: company,
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
splitLine: {
show: false //去掉网格线
}
},
yAxis: {
type: 'value'
},
series: series1
});
that.loading1 = false;
}, 1000)
}
});
} else if (row == "趋势分析(日)") {
this.tableList = false;
this.chartflag2 = true;
this.chartflag1 = false;
this.monthflag = true;
this.loading1 = true;
//日折线图掉接口
// console.log(this.month);
this.$fetchs(
"/api/pcadmin/statistics/child/line/chart/day"
).then(res => {
if (res.success == true) {
var result = res.data;
var series1 = [];
var company = [];
for (var i = 0; i < result.length; i++) {
company.push(result[i].company_name);
var data = {
}
for (let key in result[i].data) {
data[key * 1] = result[i].data[key]
}
var datas = []
for (let key in data) {
datas.push(data[key] == '' ? 0 : data[key])
}
series1.push({
name: result[i].company_name,
type: 'line',
stack: '总量',
data: datas
});
}
// 延迟一秒渲染echarts
var that = this
setTimeout(function () {
that.myChart2 = that.$echarts.init(
document.getElementById("myChart2"),
"chalk"
);
// 绘制图表
that.myChart2.setOption({
tooltip: {
trigger: 'axis'
},
legend: {
data: company,
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29',
'30', '31'
],
splitLine: {
show: false //去掉网格线
}
},
yAxis: {
type: 'value'
},
series: series1
});
that.loading1 = false;
}, 1000)
}
});
} else {
this.tableList = true;
this.chartflag1 = false;
this.chartflag2 = false;
this.monthflag = false;
}
},