我正在使用 Vue.js 在 JavaScript 应用程序中设置图表,我需要标签、图表信息始终可见,而无需鼠标悬停。
我的图表的代码如下所示:
<template>
<Pie :data="ameacas.chartData" :options="ameacas.chartOptions" style="width: 300px; height: 300px;" />
</template>
<script lang="ts">
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
import { Pie } from 'vue-chartjs'
ChartJS.register(ArcElement, Tooltip, Legend)
export default {
name: 'TdPie',
components: {
Pie
},
props: {
threats: {
type: Array,
required: true
}
},
computed: {
ameacas: function () {
return {
chartData: {
labels: ['Alta', 'Média', 'Baixa'],
datasets: [
{
backgroundColor: ['#CC092F', '#DD3820', '#FCBA03'],
data: [this.getHighThreat, this.getMediumThreat, this.getLowThreat]
}
]
},
chartOptions: {
responsive: true,
maintainAspectRatio: false
}
}
},
getHighThreat: function () {
return this.threats
.filter(threat => threat.severity && threat.severity.toLowerCase() == 'high')
.length;
},
getMediumThreat: function () {
return this.threats
.filter(threat => threat.severity && threat.severity.toLowerCase() == 'medium')
.length;
},
getLowThreat: function () {
return this.threats
.filter(threat => threat.severity && threat.severity.toLowerCase() == 'low')
.length;
}
}
}
</script>
我已经尝试过此链接中的内容以及社区中的其他内容。
我配置了“chartjs-plugin-datalabels”,代码最终如下:
<template>
<Pie :data="ameacas.chartData" :options="ameacas.chartOptions" style="width: 300px; height: 300px;" />
</template>
<script lang="ts">
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
import { Pie } from 'vue-chartjs'
import ChartDataLabels from 'chartjs-plugin-datalabels';
ChartJS.register(ArcElement, Tooltip, Legend)
ChartJS.register(ChartDataLabels);
export default {
name: 'TdPie',
components: {
Pie
},
props: {
threats: {
type: Array,
required: true
}
},
computed: {
ameacas: function () {
return {
chartData: {
labels: ['Alta', 'Média', 'Baixa'],
datasets: [
{
backgroundColor: ['#CC092F', '#DD3820', '#FCBA03'],
data: [this.getHighThreat, this.getMediumThreat, this.getLowThreat]
}
]
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
backgroundColor: function (context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 25,
borderWidth: 2,
color: 'white',
padding: 6,
formatter: Math.round
}
}
}
}
},
getHighThreat: function () {
return this.threats
.filter(threat => threat.severity && threat.severity.toLowerCase() == 'high')
.length;
},
getMediumThreat: function () {
return this.threats
.filter(threat => threat.severity && threat.severity.toLowerCase() == 'medium')
.length;
},
getLowThreat: function () {
return this.threats
.filter(threat => threat.severity && threat.severity.toLowerCase() == 'low')
.length;
}
}
}
</script>
这就是结果: