Search code examples
vue.jsvuexcomputed-properties

how to pass vuex data in computed property to data prop


I need a help to send sending data from vuex, and in computed: {} to data prop(data() {return {}})

I've tried watch: but my case doesn't work since it has to be send as props after that.

Btw, I can't get the store value in anywhere except computed property in any vue component which makes me upset...... I'm digging this issue for four hours now.. please help.

<template>
     <pie-chart :data="chartdata" />
</template>

 data() {
    return {
chartdata: [] //<<<<- I need to set the data from vuex here but calling this.$store.getters.myGetter() doesn't work
    }
},

  computed: {
    aa() {
      return this.$store.getters.getCurrentTodPlanARing;
    },
  },

I don't see any problem in my vuex. I get all the data correctly in computed only!!!. Somehow for some reason, I have only initial data which is an empty array in vuex whenever I call it in mounted, methods, or even data property(data() return {}}.

So I have to pass my vuex data to data prop...


Solution

  • If you want to use your vuex data directly you could just create a computed property and use it. YOu donn't need that extra step to store it in a data property.

    <template>
         <pie-chart :data="chartdata" />
    </template>
    
      computed: {
        chartdata() {
          return this.$store.getters.chartData;
        },
      },
    

    So everytime the vuex store gets updated, the chartData property will get updated aswell.

    If you need to modify your vuex data, before passing it to the PieChart, you could either create a watch on that computed property or simply create another computed property which, will do the work for you.

    <template>
         <pie-chart :data="modifiedChartData" />
    </template>
    computed: {
        chartdata() {
          return this.$store.getters.chartData;
        },
        modifiedChartData(){
          const data = this.chartdata;
          //Do your modifications here
           return data;
        }
      },
    

    with watch:

    <template>
         <pie-chart :data="modifiedChartData" />
    </template>
    data(){
      return {
        modifiedChartData:[]
      }
    }
    computed: {
        chartdata() {
          return this.$store.getters.chartData;
        },
      },
    watch:{
       chartdata:{
          handler (value){
            //do modifications here
            this.modifiedChartData = value;
         },
        immediate:true
       }
    }