首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Vue 3观测者中销毁和重绘Chart.js图

从Vue 3观测者中销毁和重绘Chart.js图
EN

Stack Overflow用户
提问于 2022-09-04 19:13:05
回答 1查看 97关注 0票数 1

我有一个图表显示在画布上,我想破坏和重新绘制一个Vue 3观察者。观察者工作,在更改上激发的函数工作到重绘步骤。当它到达重绘步骤时,我得到:

TypeError: Argument 1 ('element') to Window.getComputedStyle must be an instance of Element

图表对象作为component加载,并在最初挂载时从method呈现。我用的是香草chart.js (不是vue-chartjs)。

山:

代码语言:javascript
复制
  mounted() {
    this.renderChart()
  },

观看:

代码语言:javascript
复制
  watch: {
    '$store.state.weather': {
      handler(newValue, oldValue) {
        this.forecastChart.destroy()
        this.animation = 0
        this.renderChart()  // works fine until this line
      },
      deep: true
    }
  }

方法:

代码语言:javascript
复制
  methods: {
    renderChart() {
      let ctx = document.getElementById(this.id).getContext('2d');
      this.forecastChart = new Chart(ctx, {
        // source: https://stackoverflow.com/a/69047139/2827397
        type: 'doughnut',
        plugins: [{
          beforeDraw: (chart) => {
            const {ctx} = chart;

// etc.

类似的问题似乎有过时的解决办法,对我没有用。

理想情况下,我想使图表对Vuex存储状态值的变化做出反应,但是销毁和重新绘制图表将是一个可接受的结果,这就是我的问题所在。

chart.js 3.9.1,vue 3.0.0,vuex 4.0.2

编辑1:

试图.update()而不是.destroy()的图表对象也没有产生结果。

代码语言:javascript
复制
    updateChart() {
      this.forecastChart.data.datasets[0].needleValue = this.weather.airQuality - 0.5
      this.forecastChart.update()
    },

在以下方面的成果:

Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'item.fullSize = options.fullSize')

EN

回答 1

Stack Overflow用户

发布于 2022-09-07 21:19:45

我不够聪明,无法解释原因,但下面的修订解决了我面临的问题。上面,我使用以下destroy()命令引用图表对象:

代码语言:javascript
复制
this.forecastChart.destroy()

虽然这个命令没有导致控制台中显示任何错误,但在这个上下文中它显然没有正常工作(同样--这里非常重要的一点是,这是在Vue 3中完成的)。

我把上面的一行改为:

代码语言:javascript
复制
let chartStatus = Chart.getChart(this.forecastChart)
chartStatus.destroy()

现在,原来的图表被正确地摧毁了,新的图表被绘制在原来的位置。以下是相关代码的全部内容:

代码语言:javascript
复制
  watch: {
    '$store.state.weather.airQuality': {
      handler() {
        this.updateChart()
      },
      deep: true
    }
  },
  methods: {
    updateChart() {
      let chartStatus = Chart.getChart(this.forecastChart)  // key change
      chartStatus.destroy()                                 // key change
      this.animation = 0
      this.renderChart()
    },
    renderChart() {
      let ctx = document.getElementById(this.id).getContext('2d');
      this.forecastChart = new Chart(ctx, {
        type: 'doughnut',
        plugins: [{
          beforeDraw: (chart) => {
            const {ctx} = chart;

// etc.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73602130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档