成绩案例运行界面效果图如下所示:
代码如下(直接复制到html文件中即可运行):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#app {
width: 80%;
display: flex;
flex-direction: column;
align-items: center;
}
h3 {
text-align: center;
}
.content-wrapper {
display: flex;
justify-content: space-between;
width: 100%;
}
table {
border-collapse: collapse;
width: 66.66%; /* 2/3 of the page */
margin-bottom: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
tfoot td {
text-align: center;
background-color: #f2f2f2;
}
.form-wrapper {
width: 33.33%; /* 1/3 of the page */
display: flex;
flex-direction: column;
align-items: center;
}
form {
border: 1px solid #ddd;
padding: 20px;
border-radius: 5px;
margin-bottom: 20px;
width: 100%;
}
label {
margin-bottom: 5px;
}
input[type="text"] {
width: 66%;
padding: 8px;
margin-bottom: 10px;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 66%;
}
button:hover {
background-color: #45a049;
}
.red{
color: red;
}
</style>
<body>
<div id="app">
<h2>成绩计算案例</h2>
<table>
<thead>
<tr>
<th>编号</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in list" :key="item.index">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td :class="{red: item.score<60}">{{item.score}}</td>
<td><a href="#" @click="del(item.id)">删除</a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">总分:{{totalScore}} 平均分:{{avgScore}}</td>
</tr>
</tfoot>
</table>
<!-- v-model.number是转化为数字 -->
<span>科目:</span><input type="text" name="" id="" placeholder="请输入科目" v-model.trim="name"><hr>
<span>分数:</span><input type="text" name="" id="" placeholder="请输入分数" v-model.number="score"><hr>
<button @click="add">添加</button>
</div>
<!-- <script src="js/vue.min.js"></script> -->
<script src="https://cdn.staticfile.net/vue/2.7.0/vue.min.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
name:'',
score:'',
list: [
{ id: 1, name: '语文' ,score: 46},
{ id: 2, name: '英语' ,score: 80},
{ id: 3, name: '数学' ,score: 100},
]
},
computed:{
totalScore(){
return this.list.reduce((sum,item)=>sum+item.score,0)
},
avgScore(){
if(this.list.length===0){
return 0
}
return (this.totalScore/this.list.length).toFixed(2)
}
},
methods: {
del(id){
this.list = this.list.filter(item => item.id != id);
},
add(){
if(!this.name){
alert('请输入科目')
return
}
if(typeof this.score !=='number'){
alert('成绩需为数字类型')
}
this.list.unshift({
// 为了保证id的唯一性
id: new Date(),
name: this.name,
score: this.score
})
this.score='',
this.name=''
}
}
})
</script>
</body>
</html>
这个案例用到了,添加数据、删除数据、求和、求平均
多嘴一句,一定要多练习代码,加油