ChartJS 苗条和图表,传递数据

tzdcorbm  于 2023-01-30  发布在  Chart.js
关注(0)|答案(1)|浏览(155)

我试着用chart.js和svelte创建一个图表。我用3种方法调用数据,只有一种有效,而且不是我感兴趣的。在测试1中,我在外部js中有数据,它有效。(数据)在测试2中,我在svelte文件中放入了相同的数组,但它不起作用。(data2)在测试3中,我从API中获取数据,并将数组配置为与之前的格式相同。它不工作(data_chart)我需要使第三个选项工作。知道为什么它不喜欢它吗?

<script>
    import { page } from '$app/stores';
    import { onMount } from 'svelte';
    
    import { data } from './data.js';
    import { Line } from 'svelte-chartjs'
    import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale } from 'chart.js';

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

    export let param = String($page.params.slug);

    let ruta_api = `${import.meta.env.VITE_WP_API}posts?slug=${param}`;
    let ruta_api_chart = '';
    let value = [];
    let value_chart = [];
    let data_chart = new Array;
    let id_chart = [];

    const data2 = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [
      {
        label: 'My First dataset',
        borderColor: 'rgb(205, 130, 158)',
        data: [65, 59, 80, 81, 56, 55, 40],
      },
      {
        label: 'My Second dataset',
        borderColor: 'rgb(35, 26, 136)',
        data: [28, 48, 40, 19, 86, 27, 90],
      },
    ],
  };  

    onMount(async () => {
        await loadData();
    });

    async function loadData() {
        const response = await fetch(ruta_api);
        const newData = await response.json();
        value = [...value, ...newData];
        ifChart();
    }

    async function ifChart(){
        //comprobamos si viene una grafica en el contenido
        let posicion_chart = value[0].content.rendered.indexOf('m-chart-container-');

        if(posicion_chart >= 0){
            const regex = /(?<=m-chart-container-)(.*?)(?=-)/mg;
            id_chart = value[0].content.rendered.match(regex);

            //recorremos los ids
            id_chart.forEach(function(id) {
                getChart(id);
            })
        }
    };

    export async function getChart(id){
        ruta_api_chart = `${import.meta.env.VITE_WP_API}m-chart/` + id;
        const response_chart = await fetch(ruta_api_chart);
        const newData_chart = await response_chart.json();
        value_chart = newData_chart['m-chart'];

        data_chart = {'labels' : value_chart['data'][0][0], 'datasets': {'label' : value_chart['x_title'], 'data' : value_chart['data'][0][1]}};
    };

</script>

<Line {data} options={{ responsive: true }} />

<Line {data2} options={{ responsive: true }} />

<Line {data_chart} options={{ responsive: true }} />
wnavrhmk

wnavrhmk1#

这可能是因为在

<Line {data} options={{ responsive: true }} />

data={data}的简写
在其他情况下,变量名不同,因此请尝试更改为

<Line data={data2} options={{ responsive: true }} />

<Line data={data_chart} options={{ responsive: true }} />

相关问题