refactor del Fchart
This commit is contained in:
@@ -1,59 +1,56 @@
|
|||||||
<script>
|
<script>
|
||||||
import { onDestroy, onMount } from 'svelte';
|
import { onDestroy, onMount } from "svelte";
|
||||||
import Chart from 'chart.js/auto';
|
import { Chart } from "chart.js/auto";
|
||||||
|
|
||||||
let {chartData, typec='bar'} = $props();
|
let { chartData, typec = "bar" } = $props();
|
||||||
|
|
||||||
let chartContainer;
|
let chartContainer;
|
||||||
let instance;
|
let instance;
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
onDestroy(() => {
|
if (instance) {
|
||||||
if (instance) {
|
instance.destroy();
|
||||||
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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
|
||||||
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>
|
</script>
|
||||||
|
|
||||||
<div class="card card-body">
|
<div class="card card-body">
|
||||||
<canvas bind:this={chartContainer}></canvas>
|
<canvas bind:this={chartContainer}></canvas>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user