111 lines
2.9 KiB
Vue
Raw Normal View History

2021-09-04 19:40:27 +02:00
<template>
<div class="chart">
<BarChart v-bind="barChartProps" />
</div>
</template>
<script lang="ts">
import { Chart, ChartData, ChartOptions, registerables } from 'chart.js'
import { ComputedRef, PropType, computed, defineComponent } from 'vue'
import { BarChart, useBarChart } from 'vue-chart-3'
2021-09-04 21:36:59 +02:00
import { IStatisticsChartDataset, TDatasetKeys } from '@/types/statistics'
import { formatTooltipValue } from '@/utils/tooltip'
2021-09-04 19:40:27 +02:00
Chart.register(...registerables)
export default defineComponent({
name: 'Chart',
components: {
BarChart,
},
props: {
datasets: {
type: Object as PropType<IStatisticsChartDataset[]>,
required: true,
},
labels: {
type: Object as PropType<unknown[]>,
required: true,
},
2021-09-04 21:36:59 +02:00
displayedData: {
type: String as PropType<TDatasetKeys>,
required: true,
},
2021-09-04 19:40:27 +02:00
},
setup(props) {
let chartData: ComputedRef<ChartData<'bar'>> = computed(() => ({
labels: props.labels,
datasets: props.datasets,
}))
const options = computed<ChartOptions<'bar'>>(() => ({
responsive: true,
maintainAspectRatio: true,
layout: {
padding: 5,
},
scales: {
x: {
stacked: true,
grid: {
drawOnChartArea: false,
2021-09-04 19:40:27 +02:00
},
},
y: {
stacked: true,
grid: {
drawOnChartArea: false,
},
ticks: {
callback: function (value) {
return formatTooltipValue(props.displayedData, +value, false)
},
2021-09-04 19:40:27 +02:00
},
},
},
plugins: {
legend: {
display: false,
},
2021-09-04 21:36:59 +02:00
tooltip: {
interaction: {
intersect: true,
mode: 'index',
},
filter: function (tooltipItem) {
return tooltipItem.formattedValue !== '0'
},
callbacks: {
label: function (context) {
let label = context.dataset.label || ''
if (label) {
label += ': '
}
if (context.parsed.y !== null) {
label += formatTooltipValue(
props.displayedData,
context.parsed.y
)
}
return label
},
footer: function (tooltipItems) {
let sum = 0
tooltipItems.map((tooltipItem) => {
sum += tooltipItem.parsed.y
})
return 'Total: ' + formatTooltipValue(props.displayedData, sum)
},
},
},
2021-09-04 19:40:27 +02:00
},
}))
const { barChartProps } = useBarChart({
chartData,
options,
})
return { barChartProps }
},
})
</script>