<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./成绩列表.css">
</head>
<body>
<div id="app">
<table border="1">
<thead>
<tr>
<th>编号</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="item.id">
<td>{{ index + 1 }}</td>
<td>{{ item.subjectName }}</td>
<td :class="{active: item.scoreNum < 60}">{{ item.scoreNum }}</td>
<td>
<a href="#" @click.prevent="del(item.id)">删除</a>
</td>
</tr>
</tbody>
<tbody class="null" v-show="list===''">
<tr>
<td colspan="4">暂无数据</td>
</tr>
</tbody>
<tr>
<td colspan="4">
<span class="total">总计:{{totalScore}}</span>
<span class="average">平均:{{average}}</span>
</td>
</tr>
</table>
<div class="operate">
<div class="subject">
科目:<input type="text" placeholder="请输入科目" v-model.trim="subject">
</div>
<div class="score">
成绩:<input type="text" placeholder="请输入成绩" v-model.number="score">
</div>
<button @click="add">添加</button>
</div>
</div>
<!-- 引入的是开发版本包 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
<script>
const app = new Vue({
// 通过el配置选择器,指定vue管理的是哪个盒子
el: '#app',
// 通过data提供数据
data: {
list: [
{ id: 1, subjectName: '语文', scoreNum: 59 },
{ id: 2, subjectName: '数学', scoreNum: 70 },
{ id: 3, subjectName: '英语', scoreNum: 90 }
],
subject: '',
score: ''
},
methods: {
add() {
if (this.subject === '') {
alert('请输入科目')
return
}
if (typeof this.score !== 'number') {
alert('请输入正确的成绩')
return
}
this.list.push({
id: +new Date(),
subjectName: this.subject,
scoreNum: this.score
})
this.subject = ''
this.score = ''
},
del(id) {
return this.list = this.list.filter(item => item.id !== id)
}
},
computed: {
totalScore() {
return this.list.reduce((sum, item) => sum + item.scoreNum, 0)
},
average() {
if (this.list.length === 0) {
return 0
}
return this.totalScore / this.list.length
}
}
})
</script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
table {
width: 600px;
// background-color: skyblue;
margin: 20px auto;
border-collapse: collapse;
thead {
background-color: #bbb;
}
tr {
th,
td {
padding: 5px 0;
text-align: center;
}
.active {
color: rgb(221, 89, 89);
}
.total {
margin-right: 30px;
}
}
.null {
height: 100px;
text-align: center;
color: #bbb;
}
}
.operate {
display: flex;
flex-direction: column;
width: 300px;
margin: 0 auto;
input {
outline: none;
height: 30px;
}
button {
width: 50px;
}
.score {
margin: 20px 0;
}
}