Vue3+TypeScript 简易封装Echarts

507 阅读1分钟
<template>
    <div class="echarts-wrapper" ref="chartDom" :style="{ 'width': width, 'height': height }"></div>
</template>

<script setup lang="ts">
import { onDeactivated, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

interface Props {
    width?: string;
    height?: string;
    options: echarts.EChartsOption;
}

const props = withDefaults(defineProps<Props>(), {
    options: () => ({})
})

let myEcharts: echarts.ECharts
const chartDom = ref<HTMLDivElement>()
let _resizeHandler = ref()

const handlerResize = () => {
    myEcharts.resize()
}
const addResize = () => _resizeHandler.value = window.addEventListener('resize', handlerResize) // TODO debounce
const removeResize = () => { if (_resizeHandler.value) window.removeEventListener('resize', _resizeHandler.value) }

watch(() => props.options, (newValue: echarts.EChartsOption) => {
    myEcharts.setOption(newValue)
}, { deep: true })

onMounted(() => {
    myEcharts = echarts.init(chartDom.value as HTMLDivElement)
    myEcharts?.setOption(props.options, true)
    addResize()
})

onDeactivated(() => removeResize())
</script>

<style lang="scss" scoped>
.echarts-wrapper {
    width: 100%;
    height: 100%;
}
</style>