Reactive data stored using vue-chartjs and Pinia
P粉946437474
P粉946437474 2023-08-31 00:26:42
0
1
580
<p>I'm not good at using Pinia to store data with vue-chartjs to create reactive charts. I'm using this example as a guide but struggling to make the chart react to changes in the store. </p> <p>I changed the Pinia store data in another component using reactive forms and could see the store data changing but the chart did not update. </p> <p>I'm rendering the chart using the following component: </p> <pre class="brush:php;toolbar:false;"><script setup> import { storeToRefs } from 'pinia' import { useStore} from '@/store/pinia-store-file'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, tooltip, Legend } from 'chart.js'; import { Line } from 'vue-chartjs'; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, tooltip, Legend ); const store = useStore(); const storeData= storeToRefs(store); const labels = [...Array(storeData.arr.value.length).keys()]; const data = { labels: labels, datasets: [ { label: 'Data One', backgroundColor: '#f87979', data: storeData.arr.value } ] } const options = { responsive: true, maintainAspectRatio: false } </script> <template> <Line :data="data" :options="options" /> </template></pre> <p>I tried wrapping the store variable in <code>ref()</code> but I think I need to re-render the chart? I'm working on applying the above example to the Pinia store state and updating it when the store changes. </p>
P粉946437474
P粉946437474

reply all(1)
P粉338969567

You are not setting data into the response. Please use to calculate

This code can solve the problem:

<script setup>
import { storeToRefs } from 'pinia'
import { useStore} from '@/store/pinia-store-file';
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';
import { computed } from "vue"

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

const store = useStore();

const storeData= storeToRefs(store);

const data = computed(() => ({
  labels: [...Array(storeData.arr.value.length).keys()],
  datasets: [
    {
      label: 'Data One',
      backgroundColor: '#f87979',
      data: storeData.arr.value
    }
  ]
}))

const options = {
  responsive: true,
  maintainAspectRatio: false
}



</script>

<template>

  <Line :data="data" :options="options" />

</template>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template