<template>
  <div :id="id"></div>
</template>

<script>
import G2 from "@antv/g2";

export default {
  name: 'memberAgeChart',
  data() {
    return {
      chart: null
    };
  },
  props: {
    charData: {
      type: Array,
      default() {
        return []
      }
    },
    id: String,
    width: {
      type: Number,
      default: null
    }
  },
  mounted() {
    setTimeout(() => {
      this.drawChart(); // 第一步是创建的时候更新图表，但是这个不适用于异步请求接口获取相关数据，采用下面的监听的方式
    }, 30);
  },
  beforeUpdate() {
    this.drawChart();
  },
  methods: {
    drawChart() {
      // 更新的时候要移除先
      this.chart && this.chart.destroy();

      this.chart = new G2.Chart({
        container: this.id,
        width: this.width,
        forceFit: true
      });
      this.chart.source(this.charData);
      this.chart.scale('value', {
        min: 0
      });
      this.chart.scale('keyword', {
        range: [0, 1]
      });
      this.chart.tooltip({
        crosshairs: {
          type: 'line'
        }
      });
      this.chart.line().position('keyword*value');
      this.chart.point().position('keyword*value').size(4).shape('circle').style({
        stroke: '#fff',
        lineWidth: 1
      });
      this.chart.render();
    }
  }
};
</script>
