vue中Echarts封装

如题所述

第1个回答  2022-05-31
封装echars组件:

首先安装echarts  npm  echarts --save

然后新建一个echarts文件夹,新建index.vue文件:

```

<template>

  <div class="echartStyle" ref="echarts"></div>

</template>

<script lang="ts">

let Echarts = require('echarts/lib/echarts')

// 按需引入需要的组件模块

require('echarts/lib/chart/line')

require('echarts/lib/chart/scatter')

require('echarts/lib/component/title')

require('echarts/lib/component/legend')

require('echarts/lib/component/tooltip')

require('echarts/lib/component/toolbox')

require('echarts/lib/component/dataZoom')

import { defineComponent } from 'vue'

export default defineComponent({

  name: 'vue-echarts',

  props: {

    option: {//配置项

      type: Object,

      required: true

    },

    data: {//数据

      type: Array,

      required: true

    },

    series:{

      required:true

    },

    achiveOilDataSuccess: {//判断数据是否获取成功

      type: Boolean,

      required: true

    },

  },

  mounted() {

    let data = this.$props.data

    this.initOption(data)

  },

  updated() {

    let data = this.$props.data

    this.initOption(data)

  },

  methods: {

    //初始化图表配置

    initOption(data: any) {

      let vm = Echarts.init(this.$refs.echarts)

      if (this.$props.achiveOilDataSuccess === false) {

        vm.showLoading({

          text: 'loading',

          color: '#c23531',

          textColor: '#000',

          maskColor: 'rgba(255, 255, 255, 0.2)',

          zlevel: 0

        })//设置加载动画

      } else {

        vm.hideLoading()

      }

      if(this.$props.series){

        this.$props.option.series=this.$props.series

      }

      let legendNumber=this.$props.option.series.length;

      if(legendNumber===1){

         this.$props.option.series[0].data = data

      }else{

        for(let i=0;i<legendNumber;i++){

          this.$props.option.series[i].data=data[i];

        }

      }

      vm.setOption(this.$props.option)

    }

  }

})

</script>

<style lang="scss" scoped>

.echartStyle {

  width: 100%;

  height: 5rem;

  margin: 0 auto;

}

</style>

```

然后在父组件里引用

  <echarts

      :option="option"

      :data="thresholdAccInfoListHBase"

      :achiveOilDataSuccess="achiveOilDataSuccess"

    ><echarts>