[英]Creating an object from an object and an array in Vue.js 2.0
I have an array and an object created using Vue.js, I could like to combine them into one 'selection' array in the format of:我有一个数组和一个使用 Vue.js 创建的对象,我想以以下格式将它们组合成一个“选择”数组:
selection[
{food: Chicken, quantity: 3},
{food: Rice, quantity: 2},
{food: Pasta, quantity: 1}
];
I have the following set up to be able to do it:我有以下设置能够做到这一点:
var selection = []
for (var i = 0; i < meals.length; i++) {
selection.push({
food: this.meals[i],
quantity: creditsPerMeal[meals[i]]
});
},
As it stands I am getting a Syntax error but I am not convinced I should be doing this as part the data.就目前而言,我收到了语法错误,但我不相信我应该将其作为数据的一部分。 I feel that I am pretty close.
我觉得我很接近。
Here is the full code:这是完整的代码:
<template>
<div>
<div>Credits carried through: {{ credits }}</div>
<div v-for="meal in meals">
{{meal}}
<input :id="meal" :name="meal" v-model.number="creditsPerMeal[meal]" type="number">
</div>
<div>
Credits used: {{creditsSum}}
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component ready.');
console.log(JSON.parse(this.f));
},
props: ['f','c'],
name: 'credits',
data: function () {
var meals = JSON.parse(this.f)
var creditsPerMeal = {}
for (var i = 0; i < meals.length; i++) {
creditsPerMeal[meals[i]] = 0
},
var selection = []
for (var i = 0; i < meals.length; i++) {
selection.push({
food: this.meals[i],
quantity: creditsPerMeal[meals[i]]
});
},
return {
credits: this.c,
meals,
selection=,
creditsPerMeal
}
},
computed: {
creditsSum () {
return Object.values(this.creditsPerMeal).reduce((a, b) => a + b, 0)
}
}
}
</script>
UPDATE更新
As you can see from the image below if I input creditsPerMeal updates but selection doesnt, how would I bind in a way that it would.正如您从下图中看到的,如果我输入了 creditsPerMeal 更新但没有选择,我将如何以这种方式进行绑定。
Edited computed编辑计算
computed: {
creditsSum () {
return Object.values(this.creditsPerMeal).reduce((a, b) => a + b, 0)
},
createSelection: function (){
for (var i = 0; i < meals.length; i++) {
return createSelection.push({
food: meals[i],
quantity: creditsPerMeal[meals[i]]
})
}
}
}
You have indeed a syntax error in "selection=,":您确实在“selection=”中有语法错误:
return {
credits: this.c,
meals,
selection=,
creditsPerMeal
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.