如何动态更新 Chartjs 图例标签颜色?

How to dynamically update Chartjs legend label colors?

我正在使用 vue-chartjs and chartjs-plugin-colorschemes 来设置圆环图的样式。我试图让用户从 select 中选择他们喜欢的主题。我有 90% 的工作;用户可以 select 一个主题,点击更新,甜甜圈及其标签会正确改变颜色。但不起作用的是,在初始页面加载时,甜甜圈有配色方案,但图例没有。

我目前正在将默认主题作为道具传递下来,并且我正在使用 watch 方法来观察主题的变化。错误发生在这个 watch 方法内部。

如何动态更新图例标签颜色?这是我的组件的一个最小示例:

<script>
  /* eslint-disable no-new */
  import convert from 'convert-units';
  import { Doughnut } from 'vue-chartjs';
  import Chart from 'chart.js';
  import { calculateCategoryWeight } from '~/helpers/functions';
  import 'chartjs-plugin-colorschemes';

  export default {
    extends: Doughnut,

    props: {
      selected: {
        type: Object,
        default: () => {}
      },
      theme: {
        type: String,
        default: ''
      }
    },

    data () {
      const vm = this;
      return {
        chartData: {
          labels: this.selected.categories.map(category => {
            return this.$options.filters.truncate(category.name, 20);
          }),
          datasets: [
            {
              label: 'Selected Graph',
              data: this.selected.categories.map(category => {
                return parseFloat(convert(category).from('g').to('oz')).toFixed(2);
              })
            }
          ]
        },
        options: {
          cutoutPercentage: 75,
          legend: {
            display: true,
            position: 'right'
          },
          plugins: {
            colorschemes: {
              scheme: this.theme
            }
          },
          responsive: true,
          maintainAspectRatio: false,
          tooltips: {
            enabled: false
          },
        }
      };
    },

    mounted () {
      this.renderChart(this.chartData, this.options);
    },

    watch: {
      theme (newVal, oldVal) {
        const { chart } = this.$data._chart;
        chart.options.plugins.colorschemes.scheme = newVal; //<--- updates chart only
        chart.update();
      }
    }
  };
</script>

好吧,我终于找到了解决方法。

基本上在 watch 方法中,我对图表实例的挖掘太深了。通过在图表对象中上移一个级别,图例和图表颜色都会正确更新。

watch: {
  theme (newVal, oldVal) {
    const chart = this.$data._chart;  //<-- changed here
    chart.options.plugins.colorschemes.scheme = newVal;
    chart.update();
  }
}