在我们使用图表echarts组件时,其实需要对echarts进行封装,形成一个全局公共组件,如果不选择封装成组件,那么按照echarts官方文档来写则每次需要获取实例,然后echarts.init(ref)去初始化图表,这样其实会很麻烦,如果页面里的图表比较多则就会导致页面非常冗余,所以需要对其进行封装。
封装思路:
echarts其实最重要的就是它的配置项option,那么可以把其他的逻辑全部写在组件里,只需要抛出一个option值,再调用组件时只需要传配置项option就可以了。
组件目前支持图表自适应,支持点击事件,如果需要点击事件,只需要传递isClick为true,再绑定onClick事件接收点击的params。
组件源代码
<template><div ref="myEcharts" style="width: 100%;height: 100%"></div>
</template><script setup>
import * as echarts from 'echarts'
const myEcharts = ref(null);
let chartInstance = null;
const props=defineProps({option: {type: Object,required: true,default:{}},isClick:{type:Boolean,default: false}
})
const emit = defineEmits(['onClick'])
onMounted(() => {nextTick(()=>{if (myEcharts.value) {chartInstance = echarts.init(myEcharts.value);updateChart();if(props.isClick){//监听点击事件,点击到空白部分返回nullchartInstance.getZr().on('click',(e)=>{if(e.target){chartInstance.on('click',(params)=>{emit('onClick',params)//触发后卸载点击事件chartInstance.off('click');})}else{emit('onClick',null)}})}window.addEventListener('resize',resizeEcharts)}})
});const updateChart = () => {if (chartInstance && props.option) {chartInstance.setOption(props.option,true);}
};
const resizeEcharts = () =>{if (chartInstance) {chartInstance.resize();}
}watch(() => props.option,updateChart);onUnmounted(() => {if(chartInstance){if(props.isClick){chartInstance.getZr().off('click');}chartInstance.dispose()}window.removeEventListener('resize',resizeEcharts)
});</script><style scoped></style>
组件使用
组件的用法也非常简单,可以直接定义变量存储option,也可以写一个方法,内部对数据进行处理变成自己需要的数据,然后写进option里,最后可以赋给响应式数据渲染出来,也可以直接将option return出来。
<template><div style="width:100%;height:50%"><MyEchart :option='option1'></MyEchart></div><div style="width:100%;height:50%"><MyEchart :option='option2'></MyEchart></div>
</template><script setup>
import MyEchart from './component/MyEchart/index.vue'
//定义变量
const option1 = {xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},yAxis: {type: 'value'},series: [{data: [150, 230, 224, 218, 135, 147, 260],type: 'line'}]
};const option2 = ref(null)function getOption2(){//对你的数据进行处理let xValue = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];let data = [120, 200, 150, 80, 70, 110, 130]return {xAxis: {type: 'category',data: xValue,},yAxis: {type: 'value'},series: [{data: data,type: 'bar'}]};
}
option2.value = getOption2()
</script>