【问题标题】:Change Chartjs label color on click without losing hover单击时更改 Chartjs 标签颜色而不会丢失悬停
【发布时间】:2020-09-16 19:32:01
【问题描述】:

我正在使用带有labels plugin 的 vue-chart-js 来制作甜甜圈图。

当我单击一个甜甜圈部分时,该部分的背景颜色会正确更改。我还想为我单击的特定圆环图部分触发标签字体颜色更改。

这就是我为圆环图选项触发标签颜色更改的方式:

   return {
    options: {
      events: ['click'],
      plugins: {
        labels: {
          render: 'label',
          fontColor: ['black', 'black', 'black'],
        },
      },
      onClick: (evt, item) => {
        // change font color for the section to red, changes the fontColor item in array above and trigger reactivity for the options prop in the donut chart component
        this.$set(this.doughnutChart.options.plugins.labels.fontColor, 0, 'red');
      },
    },
    chartData: {
      labels: ['A', 'B', 'C'],
      datasets: [
        {
          hoverBackgroundColor: 'red',
          data: this.chartData,
        },
      ],
    },

我使用 Vue-Chartjs 文档推荐的 destroy() 和重新渲染方法来更新图表组件

export default {
  extends: Doughnut,
  mixins: [mixins.reactiveProp],
  props: {
    chartData: {
      type: Object,
      default: null,
    },
    options: {
      type: Object,
      default: null,
    },
  },
  watch: {
    options: {
      handler() {
        this._data._chart.destroy();
        this.renderChart(this.chartData, this.options);
      },
      deep: true,
    },
  },
  mounted() {
    this.renderChart(this.chartData, this.options);
  },
};

如果我点击图表部分,标签会正确变为红色。但是图表重新渲染并丢失了单击切换的红色部分背景。如果我对图表使用update() 方法,而不是销毁或重新渲染,则不会发生任何事情。

有没有办法实现点击图表并更改部分背景及其标签而无需重新渲染图表或在点击时不丢失部分背景颜色更改=

【问题讨论】:

  • codepen 示例很容易调试

标签: javascript vue.js chart.js vue-chartjs


【解决方案1】:

您可以使用update 方法。见Updating Options。实际上vue-chartjs 也将其用于chartData

在数据突变时,如果数据集中的数据发生变化,它将调用 update(),如果添加了新数据集,它将调用 renderChart()。 [source]

示例代码:

import { Doughnut, mixins } from "vue-chartjs";
import "chartjs-plugin-labels";

export default {
  extends: Doughnut,
  mixins: [mixins.reactiveProp],
  props: ["options"],
  watch: {
    options: {
      handler() {
        let chart = this.$data._chart;
        chart.options = this.options;
        chart.update();
      },
      deep: true
    }
  },
  mounted() {
    this.renderChart(this.chartData, this.options);
  }
};

CodeSandbox

【讨论】:

  • 太棒了,我只是错误地使用了update() 方法。谢谢
猜你喜欢
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2023-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 2020-08-14
相关资源
最近更新 更多