npm i echarts
npm i element-resize-detector
组件:
<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: "Chart",
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();
},
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 lang="less" scoped>
.def {
width: 100%;
height: 100%;
}
</style>
使用:
引用
import eChart from '@/components/echarts.vue'
Vue.component('e-chart', eChart)
<e-chart :options="options" style="height:265px"/>
export default {
data() {
return {
options:{}
}
},
}
图表有更新,改变options的值即可