v-for循环的input框的求和问题
首先了解一下需求:在评分表里的每一项进行评分,并将每一项的评分及对应的具体内容放到一个对象中,并将这些对象放到一个数组中,在提交时发送给后台,同时前端页面也展示合计总分。
数据结构
/*这是每一个评分项的数据结构*/
postData:{
"activityId": 0,
"anonJudgeId": "",
"itemId": 0,
"judgeId": 0,
"playerId": 0,
"score": 0,
"title": "",
"flags":false
}
最终我们要将每一项的数据作为一个对象存放到下面的数据中
postArr:[]
v-for出来的input绑定分数
/*activityData中包含了所有需要展示的评分项
scoreList是存放当前分数的数组,初始为空,双向绑定后会自定同步值
*/
<div class="form-list" v-for="(item,index) in activityData" :key="index">
<input inputmode="decimal" type="number" placeholder="0.00" v-model="scoreList[index]" @change="getSum(index,item.score,scoreList[index])">
</div>
<p class="sum"><span> 总分: </span> <span class="sum-score"> {{sumScore}}</span></p>
/*
index--当前索引
maxScore--每一项的最大得分可能也不一样,对应每一项的score,后台获取
score--当前input框的分数1
*/
//因为vue直接监控不到数组变化,所以可以用input的change或者blur事件来触发
getSum(index,maxScore,score){
let inputScore=parseFloat(this.scoreList[index]).toFixed(2)
if(inputScore>maxScore||inputScore<0){
// this.$toast.fail("请输入0-"+maxScore+"之间的分数")
//这里是对每一项的状态做判断,如果未评分或者输入超出范围,不允许提交
this.postArr[index].flags=false
return
}else{
this.postArr[index].flags=true
}
//为每一项的内容赋值
this.postArr[index].playerId=parseInt(this.playerId)
this.postArr[index].activityId=parseInt(this.activityId)
this.postArr[index].judgeId=this.judgeId
this.postArr[index].title=this.activityData[index].name
this.postArr[index].itemId=this.activityData[index].id
/*这里是每个评委的jwt_token,不需要可以不用,登录之后可以得到*/ this.postArr[index].anonJudgeId=localStorage.getItem("GradeJudge");
this.scoreList[index]=inputScore
console.log(inputScore)
this.postArr[index].score=parseFloat(inputScore)
console.log(this.postArr)
this.sumScore=0.00;
//分数求和
this.scoreList.forEach((value)=>{
this.sumScore+=parseFloat(value);
})
this.sumScore=this.sumScore.toFixed(2)
},
//因为有些属性的值是相同的,所以可以在请求到本次所需数据时,初始化一下
getActivitys(){
getActivity(this.activityId).then(res=>{
console.log("活动")
this.activityData=res.data.items
this.activityTitle=res.data.title
localStorage.setItem("activityTitle",this.activityTitle)
this.arrLength=this.activityData.length
//注意这里用深拷贝,否则最后每一项内容全是一样的
for(let i=0;i<this.arrLength;i++){
let newData=JSON.parse(JSON.stringify(this.postData))
this.postArr.push(newData)
}
})
},
//提交时判断
postRecords(){
let postFlag=true
//判断每一项的评分状态是否满足条件
this.postArr.map((value)=>{
postFlag = postFlag&&value.flags
})
console.log(postFlag)
if(!postFlag) {
console.log("请检查分数")
return
}
console.log(this.postArr)
//发起请求
},
结语
小编才疏学浅,在这里抛砖引玉,欢迎各位大佬指教!!!