Vue实现对数组的增删改查
简单做一个表格
<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>
渲染数据时,在Vue实例中创建一个students数组对象,并通过v-for标签来渲染数据到页面中
在页面添加一个添加学生按钮,点击按钮出现添加学生页面
<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>
在Vue实例对象中,定义一个空的student对象,通过v-model的双向绑定来实时对对象的数据更新,定义一个showEdit状态来显示是否时编辑窗口页面,通过isAdd状态来确定是添加还是修改
data: {
//定义一个学生数组
students: [
{
no: '1001',
name: '张三',
age: 20,
sex: '男'
}
],
//是否显示编辑窗口
showEdit: false,
//是否是添加状态
isAdd: true,
//学生对象
student: {
no: '',
name: '',
age: 0,
sex: ''
}
},
添加学生方法
addStudent() {
//将表单数据展开后,返回一个新的对象
let stu = this.student
//将学生对象添加到学生数组中
this.students.push(stu)
//调用清空表单数据的方法
this.clear()
},
删除学生方法
delStudent(index) {
if (confirm('确定删除吗?')) {
//通过数组的splice(索引号,删除个数)
this.students.splice(index, 1)
}
}
当点击表格中的修改按钮时,会调用getOne定义方法,然后根据学号索引到这个对象,并显示到编辑窗口的修改页面
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
},
clear方法清除编辑窗口数据
clear() {
this.student = {
no: '',
name: '',
age: 0,
sex: ''
}
},
显示编辑窗口固定居中
close方法
close() {
//编辑窗口关闭
this.showEdit = false
//修改为添加状态
this.isAdd = true
//清除窗口数据
this.clear()
},
#edit {
width: 300px;
height: 230px;
border: 1px solid #ccc;
padding: 20px;
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}