This commit is contained in:
2026-01-31 16:48:47 +08:00
parent 2cc924d091
commit fa4b36bd8c
5 changed files with 25 additions and 43 deletions

View File

@ -3,7 +3,7 @@
</template>
<script setup>
import * as echarts from "echarts";
import { onMounted, ref, reactive, defineProps, onUnmounted, watch, nextTick } from "vue";
import { defineProps, watch, nextTick } from "vue";
const props = defineProps({
echartsId:{
type:String,
@ -18,25 +18,14 @@ const props = defineProps({
default:[]
}
});
// 保存echarts实例
const myChart = ref(null);
// 定义resize处理函数
const handleResize = () => {
if (myChart.value) {
myChart.value.resize();
}
};
// 监听数据变化
watch(()=>props.data,val=>{
nextTick(()=>{ chartFn(val) })
},{immediate:true,deep:true})
function chartFn() {
// 如果已有实例,先销毁
if (myChart.value) {
myChart.value.dispose();
}
// 创建新实例
myChart.value = echarts.init(document.getElementById(props.echartsId));
let myChart = echarts.init(document.getElementById(props.echartsId));
var option = {
grid: {
top: "8%",
@ -86,6 +75,7 @@ function chartFn() {
},
series: [
{
name: props.name,
type: "line",
smooth:true,
showSymbol:false,
@ -115,28 +105,14 @@ function chartFn() {
}
]
};
option && myChart.value.setOption(option);
option && myChart.setOption(option);
window.addEventListener('resize',function(){
myChart.resize();
})
}
// 监听数据变化
watch(()=>props.data,val=>{
nextTick(()=>{ chartFn() })
},{immediate:true,deep:true})
// 组件挂载时初始化图表并添加事件监听
onMounted(()=>{
chartFn();
window.addEventListener('resize', handleResize);
});
// 组件卸载时清理资源
onUnmounted(()=>{
if (myChart.value) {
myChart.value.dispose();
myChart.value = null;
}
window.removeEventListener('resize', handleResize);
});
</script>
<style lang="scss" scoped>