<template>
<div class="Chart" ref="container"></div>
</template>
<script setup>
import { onMounted, onBeforeUnmount, watch, ref } from 'vue';
import * as echarts from 'echarts';
const props = defineProps({
options: {
type: Object,
default: () => {},
required: true
}
});
const container = ref(null);
let chart;
onMounted(() => {
// 初始化图表
chart = echarts.init(container.value);
chart.setOption(props.options);
});
// 监听props.options 更新图表
watch(
() => props.options,
newOptions => {
chart.setOption(newOptions);
},
{ deep: true }
);
onBeforeUnmount(() => {
//销毁图表
if (!chart) {
return;
}
chart.dispose();
chart = null;
});
</script>