概要
提示:针对不需要复用只在单一页面应用的图表(多页面应用还是做个小组件 )
因为写的Echarts图表很多,每一个图表就创建一个vue页面,很多很杂,所以想要创建一个公用的Echarts 只需要传值一个options就可以
组件构思
提示:只是简单的图表展示(需要加点击事件什么的,自己加)
定义props传值
chartDataOptions
:接受options值,默认为null
props: {
// 接收父组件传递过来的信息
chartDataOptions: {
type: Object, // 此处可以为Array或者Object或者其它,根据需求来。
default: null
}
},
难点汇总
- 一个页面多次使用的时候,要正确显示
只使用id来进行渲染Echarts会出现只显示一个图表的问题
两个方案,使用ref渲染,或者给每一个Echarts随机赋值id
我这采用随机id的方式赋值渲染
computed: {
echartsComponents() {
const timestamp = new Date().getTime();
return `echarts${timestamp}${Math.random() * 100000}`;
}
},
- 当数据传输过慢或切换options里面的数据,Echarts图表不渲染或重新渲染无效
使用watch监听刷新和$nextTick操作新实例
watch: {
chartDataOptions: {
handler() {
this.refreshEcharts();
},
deep: true
}
},
mounted() {
this.initEcharts();
this.$nextTick(() => {
this.refreshEcharts();
});
},
通用组件代码
提示:记得清空和摧毁一下Echarts实例,养成好习惯
<template>
<div
v-if="!isDispose"
:id="echartsComponents"
style="width: 100%;height: 100%"
/>
</template>
<script>
export default {
name: "EchartsComes",
props: {
// 接收父组件传递过来的信息
chartDataOptions: {
type: Object, // 此处可以为Array或者Object或者其它,根据需求来。
default: null
}
},
data() {
return {
myEcharts: null,
isDispose: false
};
},
computed: {
echartsComponents() {
const timestamp = new Date().getTime();
return `echarts${timestamp}${Math.random() * 100000}`;
}
},
watch: {
chartDataOptions: {
handler() {
this.refreshEcharts();
},
deep: true
}
},
mounted() {
this.initEcharts();
this.$nextTick(() => {
this.refreshEcharts();
});
},
beforeDestroy() {
if (this.myEcharts) {
this.myEcharts.clear();
this.myEcharts.dispose();
this.isDispose = true;
}
},
methods: {
initEcharts() {
this.isDispose = false;
const $echartsDOM = document.getElementById(this.echartsComponents);
this.myEcharts = this.$echarts.init($echartsDOM);
this.refreshEcharts();
},
// 图表刷新
refreshEcharts() {
// 渲染数据
const option = this.chartDataOptions;
this.myEcharts.clear();
this.myEcharts.setOption(option);
}
}
};
</script>
父组件调用
<card :title="'按检查内容统计安全检测'">
<template #zero>
<echarts-com :chart-data-options="zxtOption" />
</template>
</card>
效果图展示
雅,实在是太优雅了~