【问题标题】:Vuechart js not rendering on a componentVue Chart js未在组件上呈现
【发布时间】:2017-12-11 22:53:33
【问题描述】:

我正在尝试使用vue-chartjs npm 包,但我下面的代码没有呈现图表。我正在使用 VueJS 2,并且已经使用 npm 安装了该软件包。

<canvas id="chartRecord" width="100%" height="400"></canvas>

<script>
  import { Line } from 'vue-chartjs'
  export default {
    mounted () {
      Line.renderChart({
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        datasets: [{
          label: 'GitHub Commits',
          backgroundColor: '#f87979',
          data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
        }]
      })
    }
  }
</script>

我收到此错误:

[Vue 警告]:挂载钩子错误:“TypeError:__WEBPACK_IMPORTED_MODULE_0_vue_chartjs__.Line.renderChart 不是函数”

【问题讨论】:

    标签: chart.js vuejs2 vue-chartjs


    【解决方案1】:

    vue-chartjs 模块提供了 Vue 组件,这些组件旨在扩展以进行自定义。

    做你想做的事情的正确语法:

    // MyChart.js
    import { Line } from 'vue-chartjs'
    export default Line.extend({
      mounted() {
        this.renderChart({
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'GitHub Commits',
              backgroundColor: '#f87979',
              data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
            }
          ]
        })
      }
    }
    

    请注意,您可以简单地将其放在 .js 文件中,因为无需指定模板,因为它已包含在要导入的 Line 组件中,并且样式主要在图表的选项中完成。

    然后您可以像导入任何其他组件一样导入扩展组件:

    //Parent.vue
    <template>
      <my-chart></my-chart>
    </template>
    
    <script>
    import MyChart from './MyChart'
    
    export default {
      components: { MyChart }
    }
    </script>
    

    See the documentation.

    【讨论】:

    • 你能解释一下吗?我应该把那个脚本放在哪里?以及如何在我的组件中访问它。谢谢!
    • 更新了我的答案
    • 试过并在 js 文件夹中添加了Chartrecord.js。我的组件在组件文件夹中,但没有运气。
    • “没有运气”是什么意思?你有错误吗?
    • 是的,上面写着Cannot find module Unexpected token, expected , (17:0)`
    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2018-01-04
    • 2019-04-01
    相关资源
    最近更新 更多