Vue封装echart
安装ResizeListener
npm i element-resize-detector@1.2.4
VueEchart组件
<template>
<div :class="className"></div>
</template>
<script>
import { merge } from "lodash";
import * as echarts from "echarts";
import ResizeListener from "element-resize-detector";
export default {
name: "NuxtEchart",
props: {
options: {
type: Object,
default: () => ({}),
},
className: {
type: String,
default: 'def'
},
},
data() {
return {
chart: null,
};
},
watch: {
options: {
deep: true,
handler() {
this.updateChartView();
},
},
},
mounted() {
this.chart = echarts.init(this.$el);
this.updateChartView();
window.addEventListener("resize", this.handleWindowResize);
this.addChartResizeListener();
// 监听 'click' 事件
this.chart.on('click', (params) => {
this.$emit('click',params)
});
},
beforeDestroy() {
window.removeEventListener("resize", this.handleWindowResize);
},
methods: {
myChart(){
return this.chart
},
mergeOption() {
return merge(
{
//backgroundColor: "#ffffff",
// textStyle:{
// color:'#A5D7FA',
// fontSize:15
// }
},
this.options
);
},
//对chart元素尺寸进行监听,当发生变化时同步更新echart视图
addChartResizeListener() {
const instance = ResizeListener({
strategy: "scroll",
callOnAdd: true,
});
instance.listenTo(this.$el, () => {
if (!this.chart) return;
this.chart.resize();
});
},
//更新echart视图
updateChartView() {
if (!this.chart) return;
this.chart.setOption(this.mergeOption(), true);
},
// 当窗口缩放时,echart动态调整自身大小
handleWindowResize() {
if (!this.chart) return;
this.chart.resize();
},
},
};
</script>
<style scoped>
.def {
width: 100%;
height: 100%;
}
</style>
React封装echart
ReactEchart组件
import React, { useEffect,useRef } from "react";
import * as echarts from "echarts";
//自定义echart组件
export default function ReactEcharts({ option,width,height }) {
const echartRef = useRef()
useEffect(() => {
setTimeout(() => {
initChart();
});
}, [option]);
/*生成图表,做了判断,如果不去判断dom有没有生成,每次更新图表都要生成一个dom节点*/
const initChart = () => {
// 基于准备好的dom,初始化echarts实例
let myChart = echarts.getInstanceByDom(echartRef.current);
if (myChart === undefined) {
myChart = echarts.init(echartRef.current);
}
// 绘制图表,option设置图表格式及源数据
myChart.setOption(option);
//响应式
window.addEventListener('resize', function () {
myChart.resize();
});
};
return (
<div ref={echartRef} style={{ height: height?height:400,width:width?width:'100%' }}></div>
);
}