现象
echart warnning
<div id="chart" class="pie-box"></div>
onMounted(() => {
handleRoll(100); // 启动定时任务
getAbnormalDataForm();
initChart();
});
const initChart = () => {
const myChart = echarts.init(document.getElementById('chart'));
let dataList =
pieData?.createDate?.map((x) => ({
name: x.electricWheelCode,
value: x.count,
})) || [];
let colorList = [
'rgba(0, 255, 216, 0.4)',
'rgba(255, 252, 0, 0.4)',
'rgba(155,94,255,0.4)',
'rgba(0,186,255,0.4)',
'rgba(255, 148, 52,0.4)',
];
let borderColor = ['#00ffd8', '#fffc00', '#9b5eff', '#00baff', '#ff9434'];
const option = {
title: {
text: '近3月异常总数:7',
right: 62,
top: 20,
textStyle: {
color: '#ffffff',
fontSize: '24px',
},
},
legend: {
top: 'bottom',
textStyle: {
color: borderColor,
},
},
series: [
{
type: 'pie',
radius: ['70%', '55%'],
center: ['50%', '50%'],
color: colorList,
padAngle: 5,
label: {
show: true,
formatter(param) {
return param.value;
},
},
data: dataList.map((item, index) => {
item.label = {
// 第一种方法
color: borderColor[index],
position: 'outside',
fontSize: 22,
};
item.labelLine = {
show: true,
showAbove: true,
length: 39,
length2: -10,
lineStyle: {
color: colorList[index], // 改变标示线的颜色
opacity: 0,
},
};
item.itemStyle = {
borderWidth: 3,
borderColor: borderColor[index],
};
item.emphasis = {
label: {
show: true,
fontSize: 30,
fontWeight: 'bold',
},
};
return item;
}),
},
],
};
myChart.setOption(option);
};
.pie-box {
height: 380px;
width: 320px;
}
报错的的时候echart挂载的div的宽高是写在class中的。
解决方法
echart挂载的div的宽高写在行内
原因猜测
当将宽度和高度设置为内联样式时,ECharts 图表之所以能够正常工作,这主要与 DOM 元素的尺寸有关。在代码中,如果 ECharts 图表初始化时 DOM 元素的宽度 (clientWidth
) 和高度 (clientHeight
) 是 0,那么 ECharts 将无法正确渲染图表。这通常是因为 DOM 元素还没有正确渲染,或者其尺寸尚未确定。
将宽度和高度设置为内联样式后,DOM 元素的尺寸立即确定。这意味着在 ECharts 初始化时,DOM 元素的宽度和高度不再是 0,因此 ECharts 可以正确地获取 DOM 元素的尺寸,并根据这些尺寸进行图表的渲染。
内联样式的优点在于可以立即对元素的样式进行设置,并确保 DOM 元素在 ECharts 初始化时具有正确的尺寸。然而,内联样式也有一些缺点,例如可维护性和可扩展性差,因此在实际开发中,应尽量避免过多使用内联样式。
一些可能的原因及解释:
- 即时设置:当将宽度和高度设置为内联样式时,这些样式会立即应用到元素上。这样在初始化 ECharts 时,图表的容器已经有了明确的宽度和高度,ECharts 可以根据这些值进行正确的渲染。
- 排除样式冲突:内联样式通常优先级高于外部样式表,这可以避免与其他 CSS 样式的冲突,确保容器的尺寸正确。
- 避免延迟加载问题:如果外部样式表加载存在延迟,或者其他代码在初始化 ECharts 之前对样式进行了更改,可能导致 ECharts 无法获取正确的尺寸。通过设置内联样式,可以确保在 ECharts 初始化时,容器的尺寸是正确的。
总结:
虽然内联样式在一些情况下可以解决问题,但从长远角度来看,尽量避免过多使用内联样式。推荐使用外部 CSS 文件或类选择器来管理样式,以保持代码的可维护性和一致性。