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

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

export default {
  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();
  },
  watch: {
    charData() {
      this.drawChart();
    }
  },
  methods: {
    drawChart() {
      // 更新的时候要移除先
      this.chart && this.chart.destroy();
      
      this.chart = new G2.Chart({
        container: this.id,
        width: this.width,
        height: 200
      });
      this.chart.source(this.charData, {
        value: {
          formatter: function formatter(val) {
            return val.toFixed(2);
          }
        }
      });
      // this.chart.scale('key', {
      //   range: [0, 1]
      // });
      this.chart.line().position('keyword*value');
      
      this.chart.render();
    }
  }
};
</script>
