vue3 echarts 基础封装

本文介绍了如何在Vue组件中使用ECharts库创建动态图表,并实现组件的重绘以及使用防抖技术来优化窗口调整时的性能。通过watch选项更新和生命周期钩子管理,确保了图表的响应式更新和卸载时的资源清理。
摘要由CSDN通过智能技术生成

只需要传入option 对象即可
在这里插入图片描述

<template>
    <div id="myEcharts"></div>
</template>
<script setup>
import * as echarts from 'echarts';
let myChart = null;
const props = defineProps({
    option: Object,
})
//重绘
const resizeHandler = () => {
    myChart.resize();
}
//设置防抖
const debounce = (fun, delay) => {
    let timer;
    return function () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fun();
        }, delay);
    }
};
const cancalDebounce = debounce(resizeHandler, 500);

onBeforeUnmount(() => {
    window.removeEventListener('resize', cancalDebounce)
    myChart.dispose()
})

watch(() => props.option, () => {
    myChart.setOption(props.option, true);
})

onMounted(() => {
    let myChart = echarts.init(document.getElementById("myEcharts"));
    myChart.setOption(props.option, true);
    window.addEventListener('resize', cancalDebounce);
})
</script>
<style lang="less" scoped>
#myEcharts{
    width: 100%;
    height: 100%
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值