效果如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Document</title>
</head>
<style>
.box:nth-of-type(odd) {
background: yellow
}
</style>
<body>
<div id="app">
<!-- 表头 -->
<div>
<span>姓名:</span>
<input type="text" v-model.trim="user.name" required />
</div>
<div>
<span>学号:</span>
<input type="number" v-model="user.no" required />
</div>
<div>
<span>性别:</span>
<select v-model="user.sex">
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
<div>
<span>语文:</span>
<input type="number" v-model="user.language" />
</div>
<div>
<span>数学:</span>
<input type="number" v-model="user.math" />
</div>
<div>
<span>英语:</span>
<input type="number" v-model="user.english" />
</div>
<button @click="addUser">添加</button>
<button @click="editFn2">编辑</button>
<!-- 表格内容 -->
<div v-show="arr.length > 0">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>语文</th>
<th>数学</th>
<th>英语</th>
<th>操作</th>
<th>总分</th>
<th>平均分</th>
</tr>
<tr v-for="(obj, index) in arr" :key="index" :class="{on:index%2==0,off:index%2!=0}" class="box">
<td>{{index + 1}}</td>
<td>{{obj.no}}</td>
<td>{{obj.name}}</td>
<td>{{obj.sex}}</td>
<td>{{obj.language}}</td>
<td>{{obj.math}}</td>
<td>{{obj.english}}</td>
<td>
<button @click="delFn(index)">删除</button>
<button @click="editFn(obj, index)">编辑</button>
</td>
<td>{{obj.language+obj.math+obj.english}}</td>
<td>{{((obj.language+obj.math+obj.english)/3).toFixed(1)}}</td>
</tr>
</table>
</div>
</div>
</body>
<script>
const {
createApp
} = Vue
createApp({
data() {
return {
editIndex: -1,
//表单绑定对象
user: {
name: '',
no: '',
sex: '',
language: 0,
math: 0,
english: 0,
},
//数据源
arr: [{
name: '刘备',
no: '189000101',
sex: '男',
language: 124,
math: 102,
english: 90
},
{
name: '关羽',
no: '189000102',
sex: '男',
language: 115,
math: 98,
english: 95
},
{
name: '张飞',
no:'189000103',
sex: '男',
language:130,
math:86,
english:68
},
{
name: '诸葛亮',
no:'189000104',
sex: '男',
language:125,
math:145,
english:130
},
{
name: '赵云',
no:'189000105',
sex: '男',
language:118,
math:132,
english:100
},
{
name: '许莉',
no:'209010328',
sex: '女',
language:100,
math:100,
english:100
}
]
}
},
methods: {
//编辑
editFn2(){
this.$set(this.arr, this.editIndex, {
...this.user
})
this.editIndex = -1;
this.user = {
name: '',
no: '',
sex: '',
language: 0,
math: 0,
english: 0,
}
},
editFn(obj, index) {
this.user = {
...obj
};
this.editIndex = index; //正在编辑的索引
},
//删除
delFn(index) {
this.arr.splice(index, 1);
},
//添加
addUser(){
if(this.user.no!=""&&this.user.name!=""){
this.arr.push({
...this.user
});
}else{
alert("学号姓名不能为空")
}
}
},
}).mount('#app')
</script>
</html>