获取错误“this.renderChart不是函数”或“TypeError:对象(...)不是函数”Chart.js Nuxt v2

agyaoht7  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(180)

我想在我的nuxt项目版本**^2.15.7**中使用chart.js。问题是当我尝试在我的.vue页面中使用此插件时,在我的控制台中出现这些错误。
错误数:
此.renderChart不是函数
TypeError:对象(...)不是函数
这里是我的代码:
nuxt.config.js

plugins: [
    {src: '~/plugins/chart.js', mode: 'client'},
  ],

/plugins/chart.js

import Vue from 'vue'
import { Line } from 'vue-chartjs'

Vue.component('line-chart', {
    extends: Line,
    props: ['data', 'options'],
    mounted () {
        this.renderChart(this.data, this.options)
    }
})

.vue页面

<template>
    <client-only>
        <line-chart :data="chartData"></line-chart>
    </client-only>
  </template>

  <script>
  export default {
    data() {
      return {
        chartData: {
          datasets: [{
            label: 'Title',
            data: [45, 55, 48, 35, 12]
          }]
        }
      };
    }
  }
  </script>
368yc8dk

368yc8dk1#

经过多次搜索,我终于发现nuxtv 2不能导入和使用“vue-chartjs”,而不是“vue-chartjs”,我们应该使用“vue-chartjs/legacy”,这里是解决方案:
安装
1-运行
国家预防管理局第一版图表
2-然后运行
npm i图表. js hchs-vue-图表
3-/plugins/chart.js

import Vue from "vue";
import { Line } from "vue-chartjs/legacy";
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale,
  LineElement,
  PointElement,
} from "chart.js";

ChartJS.register(
  Title,
  Tooltip,
  Legend,
  PointElement,
  BarElement,
  CategoryScale,
  LinearScale,
  LineElement,
);

Vue.component("line-chart", {
  extends: Line,
});

4-. vue页面

<template>
     <client-only placeholder="منتظر بمانید...">
      <line-chart
        :chart-options="options"
        :chart-data="chartData"
        :height="250"
        :width="350"
        chart-id="lineChart"
      />
    </client-only>
  </template>

  <script>
  chartData: {
      labels: ['sun','mon','tues'],
      datasets: [
        {
          label: 'Views',
          backgroundColor: ["tomato", "orange", "yellow"],

          data: ['0','2','5']
        }
      ]
    },
    options:{
      responsive: true,
      legend: {
        display: false,
      },
      title: {
        display: true,
        text: 'views'
      },
      scales: {
        y: {
          suggestedMin: 0,
          ticks: {
            precision: 0
          }
        }
      }
    },
  </script>

5-nuxt.config.js(不要忘记模式:“客户端”)

plugins: [
    {src: '~/plugins/chart.js', mode: 'client'},
  ],

相关问题