SvelteKit:chartjs-plugin-zoom不工作

lrl1mhuk  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(138)

样本代码:

<div>
    <canvas id="example"></canvas>
</div>

<script>
    import { onMount } from 'svelte'

    import Chart from 'chart.js/auto' // Version 4.3.3

    onMount(async () => {
        const zoomPlugin = await import('chartjs-plugin-zoom') // Version 2.0.1 | Why import in onMount: https://stackoverflow.com/a/76728081/9157799

        Chart.register(zoomPlugin)

        new Chart(
            document.getElementById('example'),
            { // From https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/usage.html
                type: 'line',
                data: {
                    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                    datasets: [{
                        label: 'My First Dataset',
                        data: [65, 59, 80, 81, 56, 55, 40],
                        fill: false,
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                },
                options: {
                    plugins: {
                        zoom: {
                            zoom: {
                                wheel: {
                                    enabled: true,
                                },
                                pinch: {
                                    enabled: true
                                },
                                mode: 'xy',
                            }
                        }
                    }
                }
            }
        )
    })
</script>

没有SvelteKit,它可以工作(REPL)。

nxowjjhe

nxowjjhe1#

1.关闭页面SSR:

// +page.js
export const ssr = false;

2.正常导入zoomPlugin

<div>
    <canvas id="example"></canvas>
</div>

<script>
    import { onMount } from 'svelte'

    import Chart from 'chart.js/auto' // Version 4.3.3
    import zoomPlugin from "chartjs-plugin-zoom"

    Chart.register(zoomPlugin)

    onMount(() => {
        new Chart(
            document.getElementById('example'),
            { // From https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/usage.html
                ...
            }
        )
    })
</script>

相关问题