核心是监听父组件传入的 width、height、option 的变化并 resize
<div :style="style" ref="chartRef"></div>
import { ref,toRefs, computed, nextTick, watch } from 'vue';
import * as echarts from 'echarts';
import { useEventListener } from '@vueuse/core';
const props = defineProps({
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "100%",
},
option: {
type: Object,
default: null,
},
});
const { height, width, option } = toRefs(props);
const style = computed(() => {
return {
width: width.value,
height: height.value,
};
});
const chartRef = ref(null);
watch(option, () => {
myChart.setOption(option.value);
});
watch([width, height], () => {
myChart.resize();
});
useEventListener(window, 'resize', () => {
myChart.resize();
});
let myChart;
nextTick(() => {
myChart = echarts.init(chartRef.value);
myChart.setOption(option.value);
});
父组件中使用
<MyEcharts :width="width" :height="height" :option="option"></MyEcharts>
OK了家人们!