<style>
table{
border-collapse: collapse;
}
th,td{
padding: 2px 15px;
border: 1px solid #ccc;
text-align: center;
}
#edit{
width: 300px;
height: 230px;
border: 1px solid #ccc;
padding: 20px;
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
#edit .close{
width: 30px;
height: 30px;
border: 1px solid #ccc;
background-color: lightcoral;
color: white;
text-align: center;
line-height: 30px;
font-size: 20px;
border-radius: 50%;
cursor: pointer;
position: absolute;
right: 10px;
top: 10px;
}
</style>
<div id="app">
<button @click="showEdit=true">添加</button>
<hr>
<table>
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in students" :key="index">
<td>{{item.no}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.sex}}</td>
<td>
<button @click="getOne(item.no)">修改</button>
<button @click="delStudent(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<div id="edit" v-show="showEdit">
<!-- 在修改界面中,不能修改学号 -->
<p>学号:<input type="text" v-model="student.no" :readonly="!isAdd"></p>
<p>姓名:<input type="text" v-model="student.name"></p>
<p>年龄:<input type="text" v-model="student.age"></p>
<p>性别:<input type="text" v-model="student.sex"></p>
<p>
<button v-if="isAdd" @click="addStudent">添加</button>
<button v-else @click="updateStudent">修改</button>
<button @click="clear">取消</button>
</p>
<div class="close" @click="close">X</div>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
//定义一个学生数组
students:[
{
no:'1001',
name:'刘德华',
age:20,
sex:'男'
},
{
no:'1002',
name:'周杰伦',
age:22,
sex:'男'
},
{
no:'1003',
name:'蔡依林',
age:24,
sex:'女'
}
],
//是否显示编辑窗口
showEdit:false,
//是否是添加状态
isAdd:true,
//学生对象
student:{
no:'',
name:'',
age:0,
sex:''
}
},
methods: {
//添加方法
addStudent(){
//将表单数据展开后,返回一个新的对象
let stu = {...this.student}
//将学生对象添加到学生数组中
this.students.push(stu)
//调用清空表单数据的方法
this.clear()
},
//清空表单数据的方法
clear(){
this.student = {
no:'',
name:'',
age:0,
sex:''
}
},
//关闭编辑窗口
close(){
this.showEdit = false
this.isAdd = true
this.clear()
},
//根据学号查询学生对象
getOne(no){
//打开编辑窗口
this.showEdit = true
//编辑窗口是修改状态
this.isAdd = false
//根据学号查询学生对象
let stu = this.students.find(s=>s.no===no)
this.student = {...stu}
},
//修改学生信息
updateStudent(){
//根据学号,找到原始数组中指定的学生对象
let stu = this.students.find(s=>s.no===this.student.no)
//修改数组里面指定学生对象的属性
stu.name = this.student.name
stu.age = this.student.age
stu.sex = this.student.sex
},
//删除学生
delStudent(index){
if(confirm('确定删除吗?')){
this.students.splice(index,1)
}
}
},
})
</script>