工作中用到了,原博客地址,这里仅做记录
MyEchart
<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:{}
},
})
onMounted(() => {
nextTick(()=>{
if (myEcharts.value) {
chartInstance = echarts.init(myEcharts.value);
updateChart();
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){
chartInstance.dispose()
}
window.removeEventListener('resize',resizeEcharts)
});
</script>
组件使用
<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>