<!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">
<title>增删改查</title>
<script src="./vue2.6.14.js"></script>
<style>
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #eee;
padding: 2px 10px;
}
.box {
position: absolute;
width: 320px;
height: 200px;
border: 1px solid #ccc;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
.box .close {
width: 20px;
height: 20px;
background-color: pink;
text-align: center;
line-height: 20px;
border-radius: 50%;
cursor: pointer;
position: absolute;
right: 10px;
top: 10px;
}
.edit {
margin-top: 30px;
margin-left: 30px;
}
</style>
</head>
<body>
<div id="app">
<button v-on:click="showBox=true">添加</button>
<table>
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in user" :key="index">
<td>{{item.no}}</td>
<td>{{item.name}}</td>
<td>{{item.sex}}</td>
<td>{{item.age}}</td>
<td>
<button v-on:click="getOne(index)">修改</button>
<button v-on:click="del(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<div v-show="showBox" class="box">
<div v-on:click="close" class="close">X</div>
<table class="edit">
<tr>
<td>编号:</td>
<td><input type="text" v-model="no"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" v-model="name"></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" v-model="sex"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" v-model="age"></td>
</tr>
<tr>
<td></td>
<td>
<!-- isAdd返回true,显示添加按钮,否则显示修改按钮 -->
<button v-if="isAdd" v-on:click="add()">添加</button>
<button v-else v-on:click="update()">修改</button>
<button v-on:click="cancel()">取消</button>
</td>
</tr>
</table>
</div>
</div>
<script>
Vue.config.devtools = false
Vue.config.productionTip = false
new Vue({
el: "#app",
data: {
isAdd: true,
showBox: false,
user: [],
no: '',
name: '',
sex: '',
age: '',
// 用于备份修改时,数组中对应的下标
updateIndex: 0,
},
methods: {
add() {
let stu = {
no: this.no,
name: this.name,
sex: this.sex,
age: this.age,
}
this.user.push(stu)
},
cancel() {
this.no = '',
this.name = '',
this.sex = '',
this.age = '',
this.showBox = false;
},
getOne(index) {
// 备份当前需要修改的学生对象,在数组中的下标
this.updateIndex = index;
// 根据数组下标,获取指定对象,赋值给stu2
let stu2 = this.user[index];
// 将该用户对象身上的四个属性的值传给当前vue实例身上的四个属性
this.no = stu2.no;
this.name = stu2.name;
this.age = stu2.age;
this.sex = stu2.sex;
// 显示编辑框
this.showBox = true;
// 表示此时做的是修改操作
this.isAdd = false;
},
// 修改用户信息
update() {
// 获取数组中对应下标的学生对象
let stu3 = this.user[this.updateIndex];
stu3.no = this.no;
stu3.name = this.name;
stu3.age = this.age;
stu3.sex = this.sex;
},
// 删除学生
del(index) {
if (confirm('确定删除吗?')) {
this.user.splice(index, 1)
}
},
// 关闭编辑窗口的方法
close() {
// 隐藏编辑窗口
this.showBox = false;
// 显示添加按钮,隐藏修改按钮
this.isAdd = true;
// 清空数据
this.clear();
}
}
})
</script>
</body>
</html>
a