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

新手上路,请多包涵

我有以下 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>

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

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

     props:
['label']

然后在数据中:

 label: labels

然而这不起作用

有什么建议我可以实现这一目标吗?

原文由 Programatt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 510
2 个回答

听起来您只想修改 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;
    }
  }
}

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

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

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

原文由 Bert 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 Sergiy Seletskyy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题