传智黑马39期WEB前端教程-Vue基础-Vue指令-品牌案例-根据Id完成品牌的删除
品牌案例-根据Id完成品牌的删除
1.进入目录 DEMO,修改文件 16.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/vue-2.4.0.js"></script>
<link rel="stylesheet" href="lib/bootstrap-3.3.7.css" />
<!-- 需要用到Jquery -->
</head>
<body>
<div id="app">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加品牌</h3>
</div>
<div class="panel-body form-inline">
<label>
Id:
<input type="text" class="form-control" v-model="id" />
</label>
<label>
Name:
<input type="text" class="form-control" v-model="name" />
</label>
<!-- 在 Vue 中,使用事件绑定机制,为元素指定处理函数的时候,如果加了小括号,就可以给函数传参了 -->
<input type="button" value="添加" class="btn btn-primary" @click="add" />
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Ctime</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.ctime }}</td>
<td>
<a href="" @click.prevent="del(item.id)">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
id:'',
name:'',
list:[
{id:1, name:'奔驰', ctime:new Date()},
{id:2, name:'宝马', ctime:new Date()}
]
},
methods:{
add() { // 添加的方法
// console.log('ok');
// 分析:
// 1.获取到 id 和 name, 直接从 data 上面获取
// 2.组织出一个对象
// 3.把这个对象,调用数组的相关方法,添加到当前 data 上的 list 中
// 4.注意:在Vue中,已经实现了数据的双向绑定,每当我们修改了 data 中的数据,Vue 会默认监听到数据的改动,自动把最新的数据,应用到页面上
// 5.当我们意识到上面的第四步的时候,就证明了大家已经入门Vue了,我们更多的是在进行 VM 中 Model 数据的操作,同时,在操作 Model 数据的时候,指定的业务逻辑操作
var car = { id:this.id, name:this.name, ctime:new Date() };
this.list.push(car);
this.id = this.name = '';
},
del(id) { // 根据id删除数据
// 分析
// 1.如何根据id找到要删除这一项的索引
// 2.如果找到了索引,直接调用数组的 splice 方法
//方法一
// this.list.some((item, i)=>{
// if (item.id == id) {
// this.list.splice(i, 1);
// // 在数组的some方法,如果return true 就会立即终止这个数组的后续循环
// return true;
// }
// })
//方法二
var index = this.list.findIndex(item => {
if (item.id == id) {
return true;
}
});
this.list.splice(index, 1);
}
}
});
</script>
</body>
</html>
posted on 2019-11-20 16:19 herisson_pan 阅读(17) 评论(0) 收藏 举报
浙公网安备 33010602011771号