BarChart.vue 2.88 KB
<template>
      <div :id="chartId" class="chart-container"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    unit: {
      type: String,
      default: '万(㎡)'
    },
    tiplabel: {
      type: String,
      default: ''
    },
    chartId: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    showPercent: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      myChart: undefined
    }
  },
  watch: {
    data: {
      handler: function(newVal, oldVal) {
        this.init()
        this.setOptions()
      },
      deep: true
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.myChart = echarts.init(document.getElementById(this.chartId))
      this.setOptions()
      window.addEventListener('resize', () => {
        setTimeout(() => {
          this.myChart.resize()
        }, 300)
      })
    },

    setOptions() {
      if(!this.myChart) {
        return
      }

      let option

      if (this.data && this.data.length == 0 ) {
        option = {
          title: {
            text: '暂无数据',
            x: 'center',
            y: 'center',
            textStyle: {
              fontSize: 18,
              fontWeight: 'normal',
              color: '#1578D9'
            }
          }
        }
      } else {
        const xData = this.data ? this.data.map(item => item.name) : []
        const yData = this.data ? this.data.map(item => item.value) : []
        option = {
          title: {
            text: this.title,
            x: 'center',
            top: '20',
            textStyle: {
              fontSize: 18,
              fontWeight: 'normal',
              color: '#000'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            bottom: '10'
          },
          grid: {
            left: '65',
            bottom: '60',
            containLabel: false
          },
          xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            type: 'category',
            data: xData
          },
          series: [
            {
              name: '最高',
              type: 'bar',
              data: [180, 350]
            },
            {
              name: '平均值',
              type: 'bar',
              data: [150, 240]
            },
            {
              name: '最低',
              type: 'bar',
              data: [120, 200]
            }
          ]
        }
      }
      this.myChart.clear()
      this.myChart.setOption(option)
    }
  }
}
</script>

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