2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[vue-chart.js]グラフを削除する、再描画する

Posted at

色々な理由でグラフを削除したり再描画したいニーズの時に試行錯誤したのでメモ

やりたい事

renderChart() で表を描画した

// Chart.vue
<script>
import { Line, mixins } from 'vue-chartjs'

export default {
  name: 'chart',
  extends: Line,
  props: ['chartData', 'graphOptions'],
  mounted() {
    this.renderChart(this.chartData, this.graphOptions)
  }
}
</script>

この表のデータやオプションを変えたので、再描画したい。

解決策

1 reactivePropを使う

大体表を描画しなおしたい時は、データが変わった時。
Chart.jsでは、propsで受け取ったデータがリアクティブデータに対応できるようにmixinを用意してくれている。
propsで実装している場合は、この記述を追加する

// Chart.vue
<script>
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins // 追加

export default {
  name: 'chart',
  extends: Line,
  props: ['chartData', 'graphOptions'],
  mixins: [reqctiveProp]
  mounted() {
    this.renderChart(this.chartData, this.graphOptions)
  }
}
</script>
2 表を再描画する

ソースコードを見ればわかるが、グラフ作成時に宣言した renderChart() で2回目以降は既存の表を削除して再生成してくれる。

      renderChart (data, options) {
        if (this.$data._chart) this.$data._chart.destroy() // ここですでにグラフあるなら消している
        if (!this.$refs.canvas) throw new Error('Please remove the <template></template> tags from your chart component. See https://vue-chartjs.org/guide/#vue-single-file-components')
        this.$data._chart = new Chart(
          this.$refs.canvas.getContext('2d'), {
            type: chartType,
            data: data,
            options: options,
            plugins: this.$data._plugins
          }
        )
      }

そのため、もう一度呼んであげれば問題ない。
もう一度呼ぶメソッドみたいなのを定義してあげて呼ぶなど。

  methods: {
    reRenderChart() {
      this.renderChart(this.chartData, this.graphOptions)
    }
  }

https://github.com/apertureless/vue-chartjs/blob/9bb5b511ba1eae92b053df28ed9ab7c54f176b82/src/BaseCharts.js#L70

3 表を破棄する

本来、2で表は再描画されるのだがなぜか上手くいかなかったりする。
mixinしているため、中のソースコードは直接呼び出せるためグラフの実態を削除している this.$data._chart.destroy() も呼び出せるので直接呼び出す。(あまりいい方法ではなさそう)

  this.$data._chart.destroy() // グラフを消す
  this.renderChart(this.chartData, this.graphOptions) // もう一度作る

今回キャンバスサイズを動的に変更したかったが、うまく再生成されないのでこの手段を取った。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?