ChartJS 苗条和图表,传递数据

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

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

  1. <script>
  2. import { page } from '$app/stores';
  3. import { onMount } from 'svelte';
  4. import { data } from './data.js';
  5. import { Line } from 'svelte-chartjs'
  6. import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale } from 'chart.js';
  7. ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale);
  8. export let param = String($page.params.slug);
  9. let ruta_api = `${import.meta.env.VITE_WP_API}posts?slug=${param}`;
  10. let ruta_api_chart = '';
  11. let value = [];
  12. let value_chart = [];
  13. let data_chart = new Array;
  14. let id_chart = [];
  15. const data2 = {
  16. labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  17. datasets: [
  18. {
  19. label: 'My First dataset',
  20. borderColor: 'rgb(205, 130, 158)',
  21. data: [65, 59, 80, 81, 56, 55, 40],
  22. },
  23. {
  24. label: 'My Second dataset',
  25. borderColor: 'rgb(35, 26, 136)',
  26. data: [28, 48, 40, 19, 86, 27, 90],
  27. },
  28. ],
  29. };
  30. onMount(async () => {
  31. await loadData();
  32. });
  33. async function loadData() {
  34. const response = await fetch(ruta_api);
  35. const newData = await response.json();
  36. value = [...value, ...newData];
  37. ifChart();
  38. }
  39. async function ifChart(){
  40. //comprobamos si viene una grafica en el contenido
  41. let posicion_chart = value[0].content.rendered.indexOf('m-chart-container-');
  42. if(posicion_chart >= 0){
  43. const regex = /(?<=m-chart-container-)(.*?)(?=-)/mg;
  44. id_chart = value[0].content.rendered.match(regex);
  45. //recorremos los ids
  46. id_chart.forEach(function(id) {
  47. getChart(id);
  48. })
  49. }
  50. };
  51. export async function getChart(id){
  52. ruta_api_chart = `${import.meta.env.VITE_WP_API}m-chart/` + id;
  53. const response_chart = await fetch(ruta_api_chart);
  54. const newData_chart = await response_chart.json();
  55. value_chart = newData_chart['m-chart'];
  56. data_chart = {'labels' : value_chart['data'][0][0], 'datasets': {'label' : value_chart['x_title'], 'data' : value_chart['data'][0][1]}};
  57. };
  58. </script>
  59. <Line {data} options={{ responsive: true }} />
  60. <Line {data2} options={{ responsive: true }} />
  61. <Line {data_chart} options={{ responsive: true }} />
wnavrhmk

wnavrhmk1#

这可能是因为在

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

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

  1. <Line data={data2} options={{ responsive: true }} />
  2. <Line data={data_chart} options={{ responsive: true }} />

相关问题