You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目使用Chart.js出现Do not use 'new' for side effects错误求助

解决Vue中Chart.js的ESLint错误问题

问题概述

在Vue项目里用Chart.js绘制柱状图展示水、油占比时,碰到两个ESLint报错:

  1. Do not use 'new' for side effects (no-new):直接执行new Chart()但不赋值给变量触发
  2. 把实例赋值给myChart后,又出现myChart已赋值但未使用的错误

可行解决方案

方案1:将Chart实例挂载到组件实例(推荐)

把Chart实例存到组件的data属性里,既解决no-new问题,又让变量被“使用”(后续还能用来更新图表、销毁实例防止内存泄漏)。同时用Vue的$refs替代document.getElementById,更符合Vue的DOM操作规范。

修改后的Chart组件代码

import Chart from 'chart.js'

export default {
  name: 'Chart',
  props: {
    oil: Number,
    water: Number
  },
  data() {
    return {
      chartInstance: null // 用来存储Chart实例
    }
  },
  mounted() {
    this.renderChart()
  },
  beforeDestroy() {
    // 组件销毁时销毁Chart实例,避免内存泄漏
    if (this.chartInstance) {
      this.chartInstance.destroy()
    }
  },
  methods: {
    renderChart() {
      // 通过$refs获取canvas元素,替代getElementById
      const ctx = this.$refs.chartCanvas.getContext('2d')
      // 将实例挂载到组件的data属性上
      this.chartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['Oil', 'Water'],
          datasets: [{
            label: 'Percentage',
            data: [this.oil, this.water],
            backgroundColor: [
              'rgba(255, 99, 132, 0.2)',
              'rgba(54, 162, 235, 0.2)'
            ],
            borderColor: [
              'rgba(255, 99, 132, 1)',
              'rgba(54, 162, 235, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      })
    }
  }
}

Chart组件模板修改(添加ref)

<template>
  <div>
    <canvas ref="chartCanvas"></canvas>
  </div>
</template>

父组件代码修正

注意原代码里的<scipt>是拼写错误,要改成<script>;另外子组件的mounted钩子已经会自动执行renderChart,不需要手动调用:

<template>
  <div>
    <Chart :oil="oil" :water="water"></Chart>
  </div>
</template>

<script>
import Chart from '@/components/Chart'

export default {
  components: {
    Chart
  },
  data () {
    return {
      oil: 30,
      water: 70
    }
  }
}
</script>

方案2:用ESLint注释临时忽略错误(不推荐长期使用)

如果只是临时跳过检查,可以在对应代码行添加注释:

// eslint-disable-next-line no-new
new Chart(ctx, { ... })

或者针对未使用变量:

/* eslint-disable no-unused-vars */
const myChart = new Chart(ctx, { ... })
/* eslint-enable no-unused-vars */

这种方式只适合临时测试,长期使用会掩盖代码问题,不符合规范。

方案3:将实例挂载到全局(不推荐)

把实例挂到window对象上,但会污染全局环境,不建议在Vue项目中使用:

window.myChart = new Chart(ctx, { ... })

内容的提问来源于stack exchange,提问作者pat des pat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 23:49:58