Vue 3 chart js原因无法读取null的属性(阅读'getContext')?

798qvoo8  于 2022-11-23  发布在  Chart.js
关注(0)|答案(1)|浏览(376)

我有一个按钮可以切换传递给此ChartComponent的数据。如果在切换和重新切换后按住任何秒数,它就会工作,但如果我们做得有点快,它会导致“无法读取空值的属性(阅读'getContext')?”错误。
`

<template>
  <canvas></canvas>
</template>

<script>
import { defineComponent } from 'vue'
import Chart from 'chart.js/auto'

export default defineComponent({
  name: 'ChartComponent',
  props: {
    type: {
      type: String,
      required: true,
    },
    data: {
      type: Object,
      required: true,
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  data: () => ({
    chart: null,
  }),
  watch: {
    data: {
      handler() {
        this.chart.destroy()
        this.renderChart()
      },
      deep: true,
    },
  },
  mounted() {
    this.renderChart()
  },
  methods: {
    renderChart() {
      this.chart = new Chart(this.$el, {
        type: this.type,
        data: this.data,
        options: this.options,
      })
    },
  },
})
</script>

`

yhived7q

yhived7q1#

您应该在使用Vue 3“toRaw”函数访问此.chart之前对其进行解包/解代理:

import { toRaw } from "vue";

...

  watch: {
    data: {
      handler() {
        toRaw(this.chart).destroy()
        this.renderChart()
      },

相关问题