欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue封装echarts组件

程序员文章站 2024-01-25 20:06:40
...

echart.vue文件

<template>
    <div class="echart-box" :id="id" :option="option">
    </div>
</template>

<script>
  export default {
    name: 'echart',
    data(){
      return {
        chart: null
      }
    },
    props: {
      id: {
        type: String,
        required: true
      },
      option: {
        type: Object,
        default:()=> {
          return {}
        }
      },

    },
    watch: {
      id:function(n,o) {
        console.log('id'+ n);
      },
      option: {
        handler: function(n,o) {
          if(n != null && n != '' && Object.keys(n).length !== 0) {
            if(!this.chart) {
              let chart = this.$echarts.init(document.getElementById(this.id));
              chart.setOption(n);
              this.chart = chart
            } else {
              this.chart.clear()
              this.chart.setOption(n);
            }

          }
        },
        deep: true
      }
    },
    mounted() {
      this.$nextTick(() => {
        if (this.option != null && this.option != '' && Object.keys(this.option).length !== 0) {
          let chart = this.$echarts.init(document.getElementById(this.id));
          chart.setOption(this.option);
          this.chart = chart
        }
      })

    }
  }
</script>

<style scoped lang="less">
.echart-box {
  width: 100%;
  height: 100%;
}
</style>

其他组件中使用

  1. improt
  2. 设置样式,传入id和option,option数据变化会自动重绘
<eChart :id="'testPie'" class="e-pie" :option="pieOpt"></eChart>
<style>
.e-pie {
      height: 340px;
    }
</style>
相关标签: vue echarts