echarts踩坑记录

echarts 踩坑记录

容器没有固定宽高,并且设置了 v-show=”false”

echarts.js:2186 Can’t get DOM width or height. Please check dom.clientWidth and dom.clientHeight. They should not be 0.For example, you may need to call this in the callback of window.onload.

1
2
3
4
if (!this.isInit) {
this.isInit = true;
this.$nextTick(() => this.sankeyChart.resize());
}

on 绑定事件获取 option 数据不正确

1
2
3
4
this.sankeyChart.off("select");
this.sankeyChart.on("select", (params) => {
// 获取option
});

setoption 出错,再次执行 echarts 生成方法不能正常显示

echarts.js:3066 Uncaught Error: setOption should not be called during main process

1
2
3
4
5
6
try {
this.sankeyChart.setOption(option);
} catch (error) {
this.sankeyChart.dispose();
this.sankeyChart = echarts.init(document.getElementById("sankey-chart"));
}

容器需要设置动态宽和高

1
2
3
4
5
this.sankeyChart.getDom().style.width = maxRow * 90 + "px";
this.sankeyChart.getDom().style.height = maxCol * 90 + "px";
this.sankeyChart.resize();
this.sankeyChart.clear();
this.sankeyChart.setOption(option);

2023.8.1 补充

屏幕变化后,图表自动调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import * as ECharts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";
import Vue from "vue";
const HANDLER = "_vue_resize_handler";
function bind(el, binding) {
el[HANDLER] = binding.value
? binding.value
: () => {
let chart = ECharts.getInstanceByDom(el);
if (!chart) {
return;
}
chart.resize();
};
// 监听绑定的div大小变化,更新 echarts 大小
elementResizeDetectorMaker().listenTo(el, el[HANDLER]);
}
function unbind(el) {
elementResizeDetectorMaker().removeListener(el, el[HANDLER]);
delete el[HANDLER];
}
// 自定义指令:v-chart-resize
Vue.directive("chart-resize", { bind, unbind });