vue3 setup echarts 相关

1,055 阅读1分钟

视图层部分

<template>
    <div class="BarChart-box">
        <div ref="echart" class="BarChart-echarts" :style="`width : ${chart?.clientWidth}px`"/>
    </div>
</template>

setup js部分

<script setup>
import * as echarts from 'echarts'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'

//初始变量
let chart = null; //注意:在vue3中,图表实例的变量不能使用ref绑定,只能用普通变量,否则提示框会无效
const echart = ref(null)

//初始化图表
const initChart = () => {
    chart = echarts.init(echart.value)
    setOptions()
}

//挂载窗口变化事件
const windowResize = () => {
    window.addEventListener("resize", resizeEvent);
}

//使用requestAnimationFrame监听浏览器窗口变化
const resizeEvent = () => {
    window.requestAnimationFrame(() => {
        chart.resize();
    })
}

//设置图表
const setOptions = () => {
    chart.setOption({
        //...图表相关的配置数据...
    })
}

//渲染完成
onMounted(() => {
    nextTick(() => {
        initChart()
        windowResize()
    })
})

//被卸载
onUnmounted(() => {
    //移除窗口变化事件
    window.removeEventListener("resize",resizeEvent);
    //清空图表实例
    chart.dispose()
    chart = null
})
</script>

css部分(scss)

<style lang="scss" scoped>
.BarChart-box {
    height: 100%;
    overflow: hidden;
    position: relative;
    .BarChart-echarts {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 2;
        width: 100%;
        height: 100%;
    }
}
</style>

最后,感谢 @bypanghu 提供的代码模板