更新
This commit is contained in:
@ -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>
|
||||
|
||||
Reference in New Issue
Block a user