<template>
<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>
<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>
</template>
<script>
export default {
name: "App",
data() {
return {
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;
let stu2 = this.user[index];
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>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
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>