将数据从 Props 传递到 vue.js 中的数据

Pro*_*att 5 javascript vue.js vue-component

我有以下 vue 组件:

<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>
Run Code Online (Sandbox Code Playgroud)

如您所见,该组件实际上是另一个组件 commitChart 的包装器。提交图表采用chartOptions 的json 对象。我不希望其他组件更改标签和数据以外的任何内容,因此我希望将标签和数据作为道具传递并在数据中使用它们。

我尝试将这些作为道具添加到该组件中,然后在数据中分配它们,如下所示:

    props: 
['label']
Run Code Online (Sandbox Code Playgroud)

然后在数据中:

label: labels
Run Code Online (Sandbox Code Playgroud)

但是这不起作用

任何建议我如何实现这一目标?

Ser*_*kyy 8

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

  • 在最新版本的 Vue.js 中,您**可以**使用与声明为 props 相同的名称。它应该有效。 (4认同)

Ber*_*ert 5

听起来您只想修改对象中的几个选项chartOptions并将它们传递给您的CommitChart组件。

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的模板中使用commitChartOptions计算的。

<CommitChart :data="commitChartOptions"></Commitchart>
Run Code Online (Sandbox Code Playgroud)

这是一个演示该概念的示例