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



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

我目前正在传递一个默认主题作为道具,并使用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();
}
}

最新更新