繁体   English   中英

单击时更改 Chartjs 标签颜色而不会丢失悬停

[英]Change Chartjs label color on click without losing hover

我将 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()方法,而不是销毁或重新渲染,则不会发生任何事情。

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

您可以使用update方法。 请参阅更新选项 实际上vue-chartjs也将它用于chartData

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

示例代码:

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

代码沙盒

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM