核心是监听父组件传入的 width、height、option 的变化并 resize
<template>
<div ref="EchartRef" :style="style"></div>
</template>
<script setup>
import { useEventListener } from "@vueuse/core";
import * as echarts from "echarts";
let chartInstance;
const EchartRef = ref();
const props = defineProps({
width: {
type: [String, Number],
default: "100%",
},
height: {
type: [String, Number],
default: "100%",
},
background: {
type: String,
default: "unset",
},
option: {
type: Object,
default: () => ({}),
},
});
const { width, height, background, option } = toRefs(props);
const formatSize = (size) => (isNaN(+size) ? size : `${size}px`);
const style = computed(() => {
return {
width: formatSize(width.value),
height: formatSize(height.value),
background,
};
});
nextTick(() => {
chartInstance = echarts.init(EchartRef.value, null, { locale: "ZH" });
setOption();
});
watch([width, height], () => {
myChart.resize();
});
watch(option, setOption, { deep: true });
useEventListener(window, "resize", resize);
function resize() {
chartInstance.resize();
}
function clear() {
chartInstance.clear();
}
function setOption() {
chartInstance.setOption(option.value || {});
}
defineExpose({
setOption,
clear,
resize,
});
</script>
<style lang="scss" scoped></style>