search

Home  >  Q&A  >  body text

Reactive data stored using vue-chartjs and Pinia

<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粉946437474P粉946437474447 days ago472

reply all(1)I'll reply

  • P粉338969567

    P粉3389695672023-08-31 18:14:05

    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>
    
    

    reply
    0
  • Cancelreply