首页 > 解决方案 > 向 vue-chart-js 添加一个 chart-js 插件

问题描述

我正在尝试将一个名为 chartjs-plugin-annotation ( https://github.com/chartjs/chartjs-plugin-annotation ) 的 chartjs 插件添加到我的 vue-chart js 项目中。在我的 BarChart.vue 文件中,我首先导入了 chartjs 注释插件

<script>
import { Bar, mixins } from "vue-chartjs";
import chartjsPluginAnnotation from "chartjs-plugin-annotation";
const { reactiveProp } = mixins;
export default {
  extends: Bar,
  mixins: [reactiveProp],
  plugins: {
    annotation: {
      drawTime: "afterDatasetsDraw",
      events: ["click"],
      dblClickSpeed: 350,
      annotations: [
        {
          drawTime: "afterDraw",
          id: "a-line-1",
          type: "line",
          mode: "horizontal",
          scaleID: "y-axis-0",
          value: "25",
          borderColor: "red",
          borderWidth: 2,
          onClick: function (e) {
            // `this` is bound to the annotation element
          },
        },
      ],
    },
  },
  props: {
    options: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    // add plugin
    this.addPlugin([chartjsPluginAnnotation]);
    this.renderChart(this.chartData, this.options);
  },
  watch: {
    options() {
      this.renderChart(this.chartData, this.options);
    },
  },
};
</script>

this.addPlugin([chartjsPluginAnnotation]);在渲染图表之前,我在 mount() 下添加了插件。我是否正确地将配置选项添加到我的图表中plugins :

我已经成功安装了插件,使用npm install chartjs-plugin-annotation --save. 我在本地刷新了我的应用程序,但图表中没有添加注释插件。我应该填写onClick: function (e)什么?我还缺少什么?我提前道歉,因为我对这个框架真的很陌生。

标签: vue.jspluginsannotationschart.js

解决方案


这是您的选项对象的外观:

{
  ...
  annotation: {
    annotations: [
      {<your annotation object code here>}
    ],
  },
  ...
}

接下来,您已经正确确定应该使用该addPluing()方法,只需确保像这样使用它

// in imports
import SomePlugin from "..."

// in mounted
this.addPlugin(SomePlugin);

推荐阅读