ECharts:一个基于 JavaScript 的开源可视化图表库。
前言:这篇博客是基于父组件传值(option)给子组件即echart页面为基础的渲染图标的。话不多说,直接看代码
目录
一、介绍
1、官方文档:Apache ECharts
二、解决办法
data() {
return {
chart: null,
drawTiming: null
};
},
watch: {
options: {
handler(options) {
this.$nextTick(() => {
this.initChart();
});
},
deep: true,
},
},
mounted() {
this.$nextTick(() => {
this.initChart();
});
window.addEventListener('resize', this.resize);
},
beforeUnmount() {
window.removeEventListener('resize', this.resize);
this.chart.dispose();
this.chart = null;
clearTimeout(this.drawTiming);
this.drawTiming = null;
},
methods: {
resize() {
clearTimeout(this.drawTiming);
this.drawTiming = setTimeout(() => {
console.log('setTimeout');
let { clientWidth: width, clientHeight: height } = this.$el.parentElement;
this.chart.resize({ width, height });
}, 200);
},
initChart() {
// 初始化echart
let { clientWidth: width, clientHeight: height } = this.$el.parentElement;
this.chart.resize({ width, height });
this.chart.setOption(this.options, true); // 设置true清空echart缓存
},
},
tips
无论是在mouted还是watch初始echarts,一定要加上nextTick,否则很有可能找不到DOM节点,导致图表不能正常显示。