[Vuejs]-Still Failed to create chart: can't acquire context from the given item

1👍

In plain English, the error is telling you the chart can’t find the <canvas /> DOM element when new Chart() is run.

That’s because the <template /> contents are not available when setup() is run. They only become available after the component has been mounted (a.k.a: added to DOM), so you should place the creation of the chart inside onMounted, imported from vue.

As a side note, you shouldn’t use document.getElementById at all, it’s recommended you use template refs.

Last, but not least, you don’t need the async iife inside setup. I’m quite certain you can safely remove it.

In other words, this should do it:

import { defineComponent, ref, onMounted } from 'vue'
import Chart from 'chart.js/auto'

export default defineComponent({
  name: 'BarCharts',
  setup() {
    const data = [
      { year: 2010, count: 10 },
      { year: 2011, count: 20 },
      { year: 2012, count: 15 },
      { year: 2013, count: 25 },
      { year: 2014, count: 22 },
      { year: 2015, count: 30 },
      { year: 2016, count: 28 }
    ]
    const canvasRef = ref(null)
    onMounted(() => {
      new Chart(canvasRef.value, {
        type: 'bar',
        data: {
          labels: data.map((row) => row.year),
          datasets: [
            {
              label: 'Acquisitions by year',
              data: data.map((row) => row.count)
            }
          ]
        }
      })
    })
    return { canvasRef }
  }
})

And place the ref on the <canvas />:

  <canvas ref="canvasRef" width="400" height="400"></canvas>

Leave a comment