我正在尝试计算不等于零的子等级的平均值,并将绑定输入设置为新的平均值。
子成绩具有调用calcAverage()函数的v-on指令。在这里,我认为你应该更新相应的avgGrade值。
HTML:
<div id="container">
<div class="row" v-repeat="testData">
<p>Grade avg:
<!--this should be average of sub grades that aren't 0-->
<input type="text" v-model="avgGrade" disabled />
<div v-repeat="vals">Sub grade {{item}}:
<input type="text" v-model="grade" v-on="change:calcAverage" />
</div>
</p>
</div>
</div>
JS:
var data = [
{item: 1,avgGrade: 2,vals: [{grade: 2}, {grade: 2}, {grade: 2}]},
{item: 2,avgGrade: 3,vals: [{grade: 3}, {grade: 3}, {grade: 3}]},
{item: 3,avgGrade: 4,vals: [{grade: 4}, {grade: 4}, {grade: 4}]}
];
var testVue = new Vue({
el: '#container',
data: {
testData: data
},
methods: {
calcAverage: function (e) {
//calculate the average of sub grades
//change Grade avg to show this
}
}
});
小提琴:https://jsfiddle.net/ksumarine/bwrvsmpk/
谢谢!
答案 0 :(得分:3)
您可以将重复项目传递到change
事件回调函数,就像这样:
<强> HTML 强>
<div id="container">
<div class="row" v-repeat="testData">
<p>Grade avg:
<!--this should be average of sub grades that aren't 0-->
<input type="text" v-model="avgGrade" disabled />
<div v-repeat="vals" v-with="subItem: $data">Sub grade {{item}}:
<input type="text" v-model="grade" v-on="change:calcAverage(subItem)" />
</div>
</p>
</div>
</div>
<强> JS 强>
var data = [
{item: 1,avgGrade: 2,vals: [{grade: 2}, {grade: 2}, {grade: 2}]},
{item: 2,avgGrade: 3,vals: [{grade: 3}, {grade: 3}, {grade: 3}]},
{item: 3,avgGrade: 4,vals: [{grade: 4}, {grade: 4}, {grade: 4}]}
];
var testVue = new Vue({
el: '#container',
data: {
testData: data
},
methods: {
calcAverage: function (subItem) {
var total = 0,
length = subItem.vals.length;
for (var i = 0; i < length; i++) {
total += parseFloat(subItem.vals[i].grade);
}
subItem.avgGrade = total / length;
}
}
});
假设您的 avgGrade 是浮动的,我在这里使用parseFloat
,您可以根据需要将其更改为parseInt
。
这是一个JSFiddle。