• liang's avatar
    init · dad95e78
    liang authored
    dad95e78
BarChart.vue 2.57 KB
<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts"
import resize from "./mixins/resize"
const animationDuration = 2600
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "350px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      required: true,
    },
    chartConfig: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      chart: null,
      config: {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器,坐标轴触发有效
            type: "shadow", // 默认为直线,可选为:'line' | 'shadow'
          },
        },
        grid: {
          top: 10,
          left: "2%",
          right: "2%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: [],
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            axisTick: {
              show: false,
            },
          },
        ],
        series: [
          {
            type: "bar",
            stack: "vistors",
            barWidth: "30%",
            data: [],
            itemStyle: {
              normal: {
                barBorderRadius: 5,
              },
            },
            animationDuration: 2600,
          },
        ],
      },
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el)
      this.setOptions(this.chartData)
    },
    setOptions(chartData) {
      if (!chartData.data) return
      const option = Object.assign({}, this.config, this.chartConfig)
      const series = chartData.data.map((v) => {
        return {
          name: v.name,
          value: Number(v.value),
        }
      })
      option.xAxis[0].data = series.map((_) => _.name)
      option.series[0].data = series.map((_) => _.value)
      this.chart.setOption(option)
    },
  },
}
</script>