将数据从Props传递到vue.js中的数据 [英] Passing data from Props to data in 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对象。我不希望其他组件更改除标签和数据之外的任何内容,因此我希望将标签和数据作为道具传递并在数据中使用它们。
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']
然后在数据中:
label: labels
然而这并不是'工作
我有什么建议可以达到这个目的吗?
Any suggestions how i may achieve this?
推荐答案
听起来您只想修改 chartOptions
对象中的一些选项,并将它们传递给 CommitChart
组件。
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;
}
}
}
然后在你的模板中,使用 commitChartOptions
计算。
And then in your template, use the commitChartOptions
computed.
<CommitChart :data="commitChartOptions"></Commitchart>
这是示例展示了这个概念。
这篇关于将数据从Props传递到vue.js中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!