【问题标题】:How to dynamically update Chartjs legend label colors?如何动态更新 Chartjs 图例标签颜色?
【发布时间】:2021-03-15 00:25:42
【问题描述】:

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

我目前正在将默认主题作为道具传递,并且我正在使用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>

【问题讨论】:

    标签: chart.js vue-chartjs


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 2017-07-26
      • 1970-01-01
      相关资源
      最近更新 更多