思路
如果要删除列表中的数据,那么该如何删除呢?
删除数据需要基于数据的id号,需要将数据的id传递到删除方法中
根据id,找到要删除这一项的数组索引 index
如果找到索引index了,直接调用 数组的 splice(index,1) 方法删除数据
实例代码
在编写删除方法前,先提供示例的代码,方便读者阅读,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 1.导入vue.js库 -->
<script src="lib/vue.js"></script>
<!-- 2.导入bootstrap库 -->
<link rel="stylesheet" type="text/css" href="lib/bootstrap4/bootstrap.min.css">
<script type="text/javascript" src="lib/bootstrap4/popper.min.js"></script>
<script type="text/javascript" src="lib/bootstrap4/bootstrap.min.js"></script>
</head>
<body>
<div id="app">
<div class="container">
<!-- 搜素条件 start -->
<div class="row mt-2">
<!-- 输入添加数据的id -->
<div class="form-group row">
<label for="input_id" class="col-sm-2 col-form-label">ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="input_id" placeholder="ID" v-model="id">
</div>
</div>
<!-- 输入添加数据的name -->
<div class="form-group row ml-3">
<label for="input_name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="input_name" placeholder="Name" v-model="name">
</div>
</div>
<!-- 添加按钮 -->
<input type="button" value="添加" class="btn btn-primary ml-2 mb-3" @click="add">
<!-- 搜素关键字 -->
<input type="text" class="form-control" id="input_keywords" placeholder="输入关键字">
</div>
<!-- 搜素条件 end -->
<!-- table列表 start-->
<div class="row">
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Ctime</th>
<th scope="col">Operation</th>
</tr>
</thead>
<tbody>
<!-- 使用v-for遍历数据,并且设置key保证组件唯一性 -->
<tr v-for="item in list" :key="item.id">
<th scope="row">{{ item.id }}</th>
<td>{{ item.name }}</td>
<td>{{ item.ctime }}</td>
<td><a href="#">删除</a></td>
</tr>
</tbody>
</table>
</div>
<!-- table列表 end-->
</div>
</div>
<script>
// 2. 创建一个Vue的实例
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
// 设置列表的数据 list
list: [
{ id: 1, name: '奔驰', ctime: new Date() },
{ id: 2, name: '宝马', ctime: new Date() },
{ id: 3, name: '丰田', ctime: new Date() },
],
},
methods:{
add(){
// 将数据加入list数组
this.list.push({ id: this.id, name: this.name, ctime: new Date() });
}
}
})
</script>
</body>
</html>
实现删除的方法
1. 删除数据需要基于数据的id号,需要将数据的id传递到删除方法中
2. 根据id,找到要删除这一项的数组索引 index
在这里已经有了数组list中的id号,那么根据这个id号就可以查询到该数组在数组中的索引index。
那么基于ES6,提供了几个新方法便于数组可以根据值来定义索引,例如:some findIndex。下面来先一个简单的完成示例。
2.1 使用some方法遍历数组,当return true则终止循环
在浏览器中点击删除按钮,查看打印的数组索引,如下:
那么再来看看findIndex方法来定位数组的索引。
2.2 使用findIndex方法定位数组的索引
在浏览器中点击删除按钮,查看打印的数组索引,如下:
可以看出findIndex方法直接就将终止位置的索引index返回。
3. 使用索引index直接调用 数组的 splice(index,1) 方法删除数
根据上面找到的索引index来删除数据,如下:
本文暂时没有评论,来添加一个吧(●'◡'●)