[英]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.