vue2和vue3使用echarts

327 阅读1分钟
  1. vue@3.1.5 + echarts@5.1.1
<template>
    <div class="base-chart-wrapper" ref="divRef"></div>
</template>
export default {
    name: "",
    props: {
        chartData: {
            type: Object,
            required: true,
            default: function () {
                return {};
            },
        },
    },
    setup(props) {
        const domId = ref(props.domId);
        const divRef = ref(null);
        let myChart = null;
        onMounted(() => {
            myChart = echarts.init(divRef.value);
            let option = getOption(props.chartData);
            myChart.clear();
            myChart.setOption(option, true);
            nextTick(() => {
                myChart.resize();
            });
        });
        watch(
            () => props.chartData,
            () => {
                myChart.clear();
                let option = getOption(props.chartData);
                myChart.setOption(option, true);
                nextTick(() => {
                    myChart.resize();
                });
            },
            { deep: true }
        );
        nextTick(() => {
            myChart.resize();
        });
        window.addEventListener("resize", function () {
            myChart.resize();
        });
        return {
            domId,
            divRef,
        };
    },
};
  1. vue@2.5.2 + echarts@4.7.0
<template>
    <div class="chart-container">

    </div>
</template>

<script>

import echarts from '../../../static/lib/echarts.min.js'

export default {

    props: {
        option: Object,
        
    },
    data(){
        return {
            myChart: null,
        }
    },
    watch: {
        option: {
            deep: true,
            immediate: true,
            handler(){
                if( this.myChart ){                
                    this.myChart.clear();
                    this.myChart.setOption( this.option );
                    this.$nextTick( ()=> {

                        this._resize();
                        
                    })
                }
            }
        }
    },
    mounted(){
        this.myChart = echarts.init( this.$el );
        this.myChart.setOption( this.option );
        window.addEventListener(
            "resize",this._resize,false
        );
    },
    methods: {
        _resize(){
            this.myChart.resize();
        }
    },
    beforeDestroy(){
        window.removeEventListener(
            "resize",this._resize,false
        );

        this.myChart.dispose();

    }
}
</script>

<style lang="scss">
    .chart-container{
        height: 100%;
    }
</style>

虽说vue3 也可以使用vue2相同的代码风格,但当vue3和echarts5一起使用时,vue2的写法就会有各种各样的问题,例如: 图例不显示,tooltip鼠标移动时报错,以及还遇到了,resize的各种问题。