vue.js 仍然无法创建图表:无法从给定项目获取上下文

mepcadol  于 2023-03-24  发布在  Vue.js
关注(0)|答案(1)|浏览(120)

我看了上一篇文章后,似乎也无法让它正常工作
这里是vue模板

<template>
<div>
   <canvas id="acquisitions" width="400" height="400"></canvas>
  </div>

</template>
<script src="../pages/taara/script/acquisitions"></script>

这是剧本

import { defineComponent } from 'vue'
import Chart from 'chart.js/auto'
export default defineComponent({
  name: 'BarCharts',
  setup() {
    ;(async function () {
      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 }
      ]

      new Chart(document.getElementById('acquisitions'), {
        type: 'bar',
        data: {
          labels: data.map((row) => row.year),
          datasets: [
            {
              label: 'Acquisitions by year',
              data: data.map((row) => row.count)
            }
          ]
        }
      })
    })()
  }
})

我在文档中的给定错误后看到了这一点

Failed to create chart: can't acquire context from the given item

我发现一些帖子有同样的问题,在应用答案后仍然不起作用。请查看工作,感谢您的帮助。我是Vue和Chart.js的新手

h4cxqtbf

h4cxqtbf1#

简单地英语,错误是告诉您,当运行new Chart()时,图表找不到<canvas /> DOM元素。
这是因为setup()运行时,<template />内容不可用。它们只有在安装组件后才可用(即:添加到DOM),因此您应该将图表的创建放在从vue导入的onMounted中。
顺便说一下,你根本不应该使用document.getElementById,建议你使用template refs
最后,但并非最不重要的是,你不需要安装程序中的async生命。我很确定你可以安全地删除它。
换句话说,这应该可以做到:

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 }
  }
})

然后将ref放在<canvas />上:

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

相关问题