1.初始化生成echarts的方法需写在nextTick(dom生成后)中,否则汇报Cannot read property ‘getAttribute’ of null
2.遍历生成echarts时,宽度为0,解决办法是在echarts渲染之前先设置 div 的宽高,然后再通过 setOption 方法生成图表
<el-tabs
type="border-card"
@tab-click="handleClick"
>
<el-tab-pane label="饼状图">
<div :id="'first' + index" style="width: 1000px; height: 225px"></div>
</el-tab-pane>
<el-tab-pane label="圆环图">
<div :id="'second' + index" style="width: 1000px; height: 225px"></div>
</el-tab-pane>
<el-tab-pane label="柱状图">
<div :id="'third' + index" style="width: 1000px; height: 225px"></div>
</el-tab-pane>
<el-tab-pane label="条形图">
<div :id="'fourth' + index" style="width: 1000px; height: 225px"></div>
</el-tab-pane>
</el-tabs>
import echarts from "echarts";
export default {
data() {
return {
dataList: [
{
title: "1.您的性别是?(单选题)",
options: [
{
option: "男",
num: "28",
ratio: "49%",
},
{
option: "女",
num: "30",
ratio: "51%",
},
],
},
{
title: "2.您使用过哪些产品?(多选题)",
options: [
{
option: "QQ",
num: "12",
ratio: "30%",
},
{
option: "微信",
num: "8",
ratio: "20%",
},
{
option: "微博",
num: "20",
ratio: "50%",
},
],
},
],
};
},
methods: {
getCharts() {
//需写在nextTick(dom生成后),否则汇报Cannot read property 'getAttribute' of null
this.$nextTick(() => {
for (var i = 0; i < this.dataList.length; i++) {
let arr = [];
this.dataList[i].options?.forEach((item) => {
arr.push({
value: item.num,
name: item.option,
});
});
var chartDom = document.getElementById("first" + i);
var option, myChart;
if (arr.length > 0) {
myChart = echarts.init(chartDom);
option = {
tooltip: {
trigger: "item",
formatter: "{a} <br/>{b} : {c} ({d}%)",
},
legend: {
top: "5%",
left: "center",
},
series: [
{
name: "",
type: "pie",
radius: "50%",
data: arr,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
],
};
myChart.setOption(option);
}
}
});
},
},
mounted(){
this.getCharts()
}
}