封装组件的时候获取的元素不要用ref
<script setup>
import * as echart from 'echarts';
import { ref, onMounted, onBeforeUnmount, watch} from 'vue';
const props = defineProps({
id: {
type: String,
default: ''
},
options: {
type: Object,
required: true,
},
height: {
type: String,
},
width: {
type: String,
},
})
onMounted(() => {
initCharts();
});
// 初始化图表
const initCharts = () => {
myChart = echart.init(document.getElementById(props.id));
renderEchart();
// 页面大小变化重置图表
window.addEventListener("resize", () => {
myChart.resize();
});
}
// 设置echarts配置项
const renderEchart = () => {
myChart.setOption(props.options);
}
const clearEchart = () => {
myChart.clear();
}
onBeforeUnmount(() => {
// 销毁echarts实例
myChart = null
})
</script>
<template>
<div :id="id" v-if="options" :style="{ 'height': height, 'width': width }"></div>
</template>
<style lang='scss' scoped></style>