Passing data from Props to data in vue.js

19,592

Solution 1

It sounds like you want to modify just a few of the options in your chartOptions object and pass them as to your CommitChart component.

export default {
  props:["label","data"],
  data() {
    return {
      chartOptions: {...},
    }
  },
  computed:{
    commitChartOptions(){
      let localOptions = Object.assign({}, this.chartOptions)
      localOptions.datasets[0].label = this.label;
      localOptions.datasets[0].data = this.data;
      return localOptions;
    }
  }
}

And then in your template, use the commitChartOptions computed.

<CommitChart :data="commitChartOptions"></Commitchart>

Here is an example demonstrating the concept.

Solution 2

export default {
  props: ['label'],
  data () {
    return {
      anotherLabel: this.label, // you cannot use the same name as declared for props
    }
  }
}
Share:
19,592
Programatt
Author by

Programatt

Updated on June 07, 2022

Comments

  • Programatt
    Programatt almost 2 years

    I have the following vue component:

    <template>
      <div class ="container bordered">
        <div class="row">
          <div class="col-md-12">
      <CommitChart :data="chartOptions"></Commitchart>
      </div>
    </div>
    </div>
    </template>
    <script>
    import CommitChart from './CommitChart';
    
    export default {
      data() {
        return {
          chartOptions: {
            labels:  ['pizza', 'lasagne', 'Cheese'],
            datasets: [{
              label: '# of Votes',
              data: [12, 19, 3],
              backgroundColor: [
                    'rgba(10, 158, 193, 1)',
                    'rgba(116, 139, 153, 1)',
                    'rgba(43, 94, 162, 1)',
    
                ],
                borderColor: [
                  'rgba(44, 64, 76, 1)',
                  'rgba(44, 64, 76, 1)',
                  'rgba(44, 64, 76, 1)',
    
                ],
                borderWidth: 3
            }],
        },
        };
      },
      components: { CommitChart },
    };
    </script>
    <style scoped>
    </style>
    

    as you can see, this component is effectively a wrapper for another component which is commitChart. Commit chart takes a json object of chartOptions. I don't want the other components to change anything but the labels and data, so I therefore would like to pass label and data as props and use these in data.

    i tried adding these as props to this component and then in data, assigning them, something like this:

        props: 
    ['label']
    

    and then in data:

    label: labels
    

    however this doesn't work

    Any suggestions how i may achieve this?