barChart.vue 2.34 KB
<template>
  <div class="chart-box">
    <div id="bar" class="chart-bar"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts'

export default {
  name: 'BarChart',
  props: ['list'],
  data() {
    return {
      myChart: {},
      option: {
        xAxis: {
          max: 'dataMax',
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'category',
          data: [],
          inverse: true,
          splitLine: {
            show: false
          },
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 4 // only the largest 3 bars will be displayed
        },
        grid: {
          x: 120,
          y: 0,
          x2: 20,
          y2: 0
        },
        series: [
          {
            realtimeSort: true,
            name: 'X',
            type: 'bar',
            data: [],
            label: {
              show: true,
              position: 'right',
              valueAnimation: true
            },
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  textStyle: {
                    color: '#fff',
                    fontSize: 16
                  }
                },
                color: '#5850FF' // 修改柱状颜色
              }
            }
          }
        ],
        // legend: {
        //   show: true
        // },
        animationDuration: 0,
        animationDurationUpdate: 3000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear'
      }
    }
  },
  watch: {
    list(val) {
      if (val) {
        const yData = val.map(i => i.packageName)
        const data = val.map(i => i.totalSales)
        this.option.yAxis.data = yData
        this.option.series[0].data = data
        this.option && this.myChart.setOption(this.option)
      }
    }
  },
  methods: {
    getChart() {
      let option
      const data = []
      for (let i = 0; i < 5; ++i) {
        data.push(Math.round(Math.random() * 200))
      }
    }
  },
  mounted() {
    // this.getChart()
    let chartDom = document.getElementById('bar')
    this.myChart = echarts.init(chartDom)
    this.option && this.myChart.setOption(this.option)
  }
}
</script>

<style lang="scss" scoped>
.chart-box {
  width: 100%;
  height: 240px;
}
.chart-bar {
  height: 240px;
}
</style>