ChartJS Svelte中的React性图表

irtuqstp  于 2023-02-16  发布在  Chart.js
关注(0)|答案(1)|浏览(256)

我有麻烦的React图表在苗条。我希望图表更新显着时,数据的能量变化。什么是失踪在这个代码?

<script lang="ts">
import { Line } from "svelte-chartjs";
import { onMount } from "svelte";

let labels = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
let energy =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let data = {
    labels,
    datasets: [
        {
            label: "Dataset",
            data: energy,
            borderColor: "rgb(255, 99, 132)",
            backgroundColor: "rgba(255, 99, 132, 0.5)"
        },
    ]
};

$:labels,energy,data

onMount(() => {
    const interval = setInterval(() => {
        rendom();
        console.log(energy)
    }, 1000);
    return () => {
      clearInterval(1);
    };
})
    

function rendom() {
    let index=Math.round(Math.random()*9);
    energy[index]=Math.round(Math.random()*100)
}

</script>

<Line data={data}/>

我的问题的答案。

dgjrabp2

dgjrabp21#

看看Line Chart Example,从chart.jsChartJS.register()进行一些导入似乎是必要的
svelte-chartjs中的Line组件导出对图表的引用,更改数据后可在该图表上调用.update()。可通过局部变量和bind:访问该引用
注意,clearInterval()引用间隔(并且可以将rendom更改为random,如Math.random()中所示)
REPL

<script>
    import {
        Chart as ChartJS,
        Title,
        Tooltip,
        Legend,
        LineElement,
        LinearScale,
        PointElement,
        CategoryScale,
    } from 'chart.js';

    ChartJS.register(
        Title,
        Tooltip,
        Legend,
        LineElement,
        LinearScale,
        PointElement,
        CategoryScale
    );

    import { Line } from "svelte-chartjs";
    import { onMount } from "svelte";

    let labels = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
    let energy =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    let chartRef

    let data = {
        labels,
        datasets: [
            {
                label: "Dataset",
                data: energy,
                borderColor: "rgb(255, 99, 132)",
                backgroundColor: "rgba(255, 99, 132, 0.5)"
            },
        ]
    };

    onMount(() => {
        const interval = setInterval(() => {
            rendom();
        }, 1000);
        return () => {
            clearInterval(interval);
        };
    })

    function rendom() {
        let index=Math.round(Math.random()*9);
        energy[index]=Math.round(Math.random()*100)
        chartRef.update()
    }

</script>

<Line bind:chart={chartRef} data={data}/>

相关问题