美文网首页
vue-echarts组件实现

vue-echarts组件实现

作者: 长街漫步 | 来源:发表于2019-08-05 17:43 被阅读0次
<template>
  <div class="echarts" style="width:100%">
    <div :id="counterId" :style="{width: echart_width, height: echart_height}"></div>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
    name: "echarts",
    props: {
        /**
         * @description 默认宽度 px
         */
        echart_width: {
            type: String,
            default: "100%"
        },
        /**
         * @description 默认高度 px
         */
        echart_height: {
            type: String,
            default: "100%"
        },
        /**
         * @description 配置项
         */
        options: {}
    },
    computed: {
        counterId() {
            return `echarts_${this._uid}`;
        }
    },
    created() {},
    data() {
        return {
            chart: ""
        };
    },
    watch: {
        //观察option的变化
        options: {
            handler(newVal, oldVal) {
                if (this.chart) {
                    if (newVal) {
                        this.chart.setOption(newVal);
                    } else {
                        this.chart.setOption(oldVal);
                    }
                } else {
                    this.init();
                }
            },
            deep: true //对象内部属性的监听,关键。
        }
    },
    mounted() {
        this.init(this.options);
    },
    methods: {
        init(options) {
            // console.log(options);
            this.chart = echarts.init(document.getElementById(this.counterId));
            this.chart.setOption(options);
            // window.onresize = myChart.resize; // 自适应
            const self = this;
            window.addEventListener("resize", function() {
                self.chart.resize();
            });
        }
    }
};
</script>

相关文章

网友评论

      本文标题:vue-echarts组件实现

      本文链接:https://www.haomeiwen.com/subject/hpqzqqtx.html