refactor del Fchart
This commit is contained in:
@@ -1,59 +1,56 @@
|
||||
<script>
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import Chart from 'chart.js/auto';
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { Chart } from "chart.js/auto";
|
||||
|
||||
let {chartData, typec='bar'} = $props();
|
||||
let { chartData, typec = "bar" } = $props();
|
||||
|
||||
let chartContainer;
|
||||
let instance;
|
||||
let chartContainer;
|
||||
let instance;
|
||||
|
||||
|
||||
onDestroy(() => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
const createChart = () => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
}
|
||||
|
||||
const ctx = chartContainer.getContext('2d');
|
||||
instance = new Chart(ctx, {
|
||||
type: typec,
|
||||
data: {
|
||||
labels: chartData.labels,
|
||||
datasets: chartData.datasets.map(dataset => ({
|
||||
label: dataset.label,
|
||||
data: dataset.data.map(x => String(x)),
|
||||
borderWidth: dataset.borderWidth
|
||||
}))
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'top',
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
onDestroy(() => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
}
|
||||
});
|
||||
};
|
||||
onMount(createChart);
|
||||
$effect(createChart);
|
||||
|
||||
const createChart = () => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
}
|
||||
|
||||
const ctx = chartContainer.getContext("2d");
|
||||
instance = new Chart(ctx, {
|
||||
type: typec,
|
||||
data: {
|
||||
labels: chartData.labels,
|
||||
datasets: chartData.datasets.map((dataset) => ({
|
||||
label: dataset.label,
|
||||
data: dataset.data.map((x) => String(x)),
|
||||
borderWidth: dataset.borderWidth,
|
||||
})),
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: "top",
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
onMount(createChart);
|
||||
$effect(createChart);
|
||||
</script>
|
||||
|
||||
<div class="card card-body">
|
||||
<canvas bind:this={chartContainer}></canvas>
|
||||
<canvas bind:this={chartContainer}></canvas>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user