Passing data from Props to data in vue.js

偶尔善良 提交于 2019-12-10 17:42:46

问题


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?


回答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.




回答2:


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



回答3:


let assume: labels is data and label is props

then use this to copy:

this.labels = { ...this.label };



回答4:


Props are declared like this:

props: ['label']

not

props: {label}

here is working fiddle: jsfiddle



来源:https://stackoverflow.com/questions/43496656/passing-data-from-props-to-data-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!