echarts组件封装完整版

<template>
    <div :id="id" :style="style"></div>
</template>

<script>
import * as echarts from 'echarts';
export default {
    name: 'charts',
    props: {
        // id名
        id: {
            type: String
        },
        // 宽度
        width: {
            type: String,
            default: '100%'
        },
        // 高度
        height: {
            type: String,
            default: '100%'
        },
        // 数据
        option: {
            type: Object
        },
        // 是否开启轮播
        carousel: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            chart: null,
            timer: 0
        };
    },
    computed: {
        style() {
            return {
                width: this.width,
                height: this.height
            };
        }
    },
    watch: {
        option: {
            handler(newVal, oldVal) {
                if (this.chart) {
                    this.chart.setOption(newVal);
                } else {
                    this.initChart();
                }
            },
            deep: true
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.initChart();
            // 是否开启自动轮播
            if (this.carousel) {
                this.getVoluntarily();
            }
        });
    },
    beforeDestroy() {
        if (!this.chart) {
            return;
        }
        this.chart.dispose();
        this.chart = null;
        clearInterval(this.timer);
    },
    methods: {
        initChart() {
            this.chart = echarts.init(document.getElementById(this.id));
            this.chart.setOption(this.option);
            window.addEventListener('resize', this.chart.resize);
        },
        getVoluntarily() {
            const _length = this.chart.getOption().series[0].data.length;
            let count = 0;
            this.timer = setInterval(() => {
                this.chart.dispatchAction({
                    type: 'showTip', // 提示框
                    seriesIndex: 0,
                    dataIndex: count // 第几行柱子高亮
                });
                this.chart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: count - 1
                });
                this.chart.dispatchAction({
                    type: 'highlight',
                    seriesIndex: 0,
                    dataIndex: count
                });
                if (_length === count) {
                    count = 0;
                } else {
                    count++;
                }
            }, 3000);
        }
    }
};
</script>

在页面中引用

<ChartsPart :id="id" :height="height" :option="option" carousel='true'/>


版权声明:本文为m0_73121002原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。