spark-line.vue 2.01 KB
<template>
  <canvas ref="canvas" />
</template>

<script>
const F2 = require('@antv/f2/lib/core');

require('@antv/f2/lib/geom/line');
require('@antv/f2/lib/scale/time-cat');

const Animation = require('@antv/f2/lib/animation/detail');
const Tooltip = require('@antv/f2/lib/plugin/tooltip');

F2.Chart.plugins.register(Animation);
F2.Chart.plugins.register(Tooltip);

export default {
  name: 'SparkLine',
  methods: {
    initChart() {
      const chart = new F2.Chart({
        el: this.$refs.canvas,
        pixelRatio: window.devicePixelRatio,
      });

      chart.tooltip({
        custom: true,
        showXTip: true,
        showYTip: true,
        snap: true,
        crosshairsType: 'xy',
        crosshairsStyle: {
          lineDash: [2],
        },
      });

      chart.axis('date', {
        label: function label(text, index, total) {
          const textCfg = {};

          if (index === 0) {
            textCfg.textAlign = 'left';
          } else if (index === total - 1) {
            textCfg.textAlign = 'right';
          }
          return textCfg;
        },
      });

      this.chart = chart;
    },
    changeData(...args) {
      if (this.rendered) {
        this.chart.changeData(...args);
      } else {
        this.repaint(...args);
      }
    },
    repaint(data = [], { valueTickCount = 5, dataTickCount = 5 } = {}) {
      if (!this.rendered) {
        this.rendered = true;
      } else {
        this.chart.clear();
      }

      this.chart.source(data, {
        value: {
          tickCount: valueTickCount,
        },
        date: {
          type: 'timeCat',
          range: [0, 1],
          tickCount: dataTickCount,
        },
      });
      this.chart.line().position('date*value');
      this.chart.render();
    },
    destroyChart() {
      if (this.chart) {
        this.chart.destroy();
        this.chart = null;
      }
    },
  },
  mounted() {
    this.initChart();
    this.$emit('init', {chart: this.chart, component: this});
  },
  beforeDestroy() {
    this.destroyChart();
  },
};
</script>