<template>
<div :id="id" :class="className" :style="{ height, width, 'max-width': '100%' }"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
props: {
id: {
type: String,
default: 'chart',
required: true
},
className: {
type: String,
default: ''
},
width: {
type: String,
default: '100%',
},
height: {
type: String,
default: '300px',
},
loading: {
type: Boolean,
default: true,
},
fullOptions: {
type: Object,
default: () => {
return {}
},
required: true
},
},
data() {
return {
myChart: null
}
},
watch: {
fullOptions: {
handler() {
this.myChart?.hideLoading();
let option = props.fullOptions;
this.myChart?.setOption(option, true);
this.resizeHandler()
},
immediate: true,
deep: true
},
loading: {
handler() {
this.myChart?.hideLoading();
this.resizeHandler()
},
immediate: true,
deep: true
}
},
mounted() {
//配置为 svg 形式,预防页面缩放而出现模糊问题;图表过于复杂时建议使用 Canvas
this.myChart = echarts.init(document.getElementById(props.id), { renderer: 'svg' })
this.myChart.showLoading({
text: '',
color: '#409eff',
textColor: '#000',
maskColor: 'rgba(255, 255, 255, .95)',
zlevel: 0,
lineWidth: 2,
});
if (!props.loading) {
this.myChart.hideLoading();
let option = props.fullOptions;
this.myChart.setOption(option, true);
}
window.addEventListener('resize', this.resizeHandler);
},
//页面销毁前,销毁事件和实例
beforeUnmount() {
window.removeEventListener('resize', this.resizeHandler)
myChart?.dispose()
},
methods: {
resizeHandler() {
//找到图标canvas 设置自适应
document.getElementById(this.id).children[0].style.width = '100%';
document.getElementById(this.id).children[0].children[0].style.width = '100%';
setTimeout(() => {
this.myChart?.resize();
}, 0);
}
}
}
</script>
<style></style>
一、组件props:
1、每个echart都是一个单独的id,
2、 echarts的配置项,
3、 如果数据是接口返回, 那么数据的loading加载效果也是必须的, 组件内部也可以简单修改loading的样式,
二、
1、关于这个组件内有些丑陋的代码,建议不要删,总有一些离谱的bug影响图表的渲染