HTML
<div id="app">
<table>
<thead>
<tr>
<th>编号</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody v-if="list.length > 0">
<tr v-for="(item,index) in list " :key="item.id">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td :class="{red: item.agm < 60}">{{item.agm}}</td>
<td><button @click="shchu(item.id)">删除</button></td>
</tr>
</tbody>
<tbody v-else="list.length < 0">
<tr>
<td colspan="5">
<p>没有数据</p>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<span>总分:{{suan}}</span>
<span>平均分:{{ping}}</span>
</td>
</tr>
</tfoot>
</table>
<div>
<form action="">
<!-- trim 去掉首尾空格 number 转数字不会强转 -->
<p>科目:<input v-model.trim="mu" type="text" placeholder="请输入科目"></p>
<p>成绩:<input v-model.number="ji" type="text" placeholder="请输入成绩"></p>
<button type="button" @click="add">添加</button>
</form>
</div>
</div>
css
table{
width: 400px;
border-collapse: collapse;
}
table tr td{
height: 30px;
text-align: center;
border: 1px solid rgb(205, 202, 202);
}
table thead tr th{
height: 40px;
border: 1px solid rgb(205,202,202);
background-color: rgb(134, 133, 133);
}
.red{
color: red;
}
js
const app = new Vue({
el:'#app',
data:{
list:[
{id:1,name:'数学',agm:30},
{id:2,name:'英语',agm:80},
{id:3,name:'历史',agm:90},
],
mu:'',
ji:'',
},
methods:{
shchu(id){
console.log(id);
// 删除数据
this.list= this.list.filter(item =>item.id !==id)
},
add(){
if(!this.mu){
alert("请输入科目")
return
}
if(typeof this.ji !== 'number'){
alert("请输入数字成绩")
return
}
// 添加数据
this.list.unshift({
id: +new Date(),
name:this.mu,
agm:this.ji
})
// 清空输入框
this.mu='',
this.ji=''
}
},
// 计算
computed:{
//总合 箭头函数
suan(){
//reduce 累加器 返回总和
return this.list.reduce((sum,item)=>sum +item.agm,0)
},
// // 不是箭头函数
// suan(){
// function suan(){
// return this.list.reduce(sum,item)= sum+item.agm
// }
// },
//平均值
ping(){
if(this.list.length === 0)
{
return 0
}
return (this.suan / this.list.length).toFixed(2)
}
}
})