vue 基础入门笔记 06:todo-list 小 demo、some ()、findIndex ()
vue 基础入门笔记 06
- 简单的新增 删除 检索
<!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="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</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 for="">
ID:
<input type="text" v-model='id' name="" id="">
</label>
<label>
Name
<input type="text" v-model='name' name="" id="input" class="form-control" value=""
required="required" pattern="" title="">
</label>
<button type="button" @click='add' class="btn btn-primary">添加</button>
<label for="input-id">
搜索关键字
<input v-model="keywords" type="text" name="" id="input" class="form-control"
required="required" >
</label>
</div>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>ctime</th>
<th>opt</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="item in search(keywords)" :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() },
],
keywords: ''
},
methods: {
// 搜索
search(keywords){
// 过滤符合条件的新数组
return this.list.filter(item=>{
// 字符串包含返回true
if(item.name.includes(keywords))
return item
})
},
// 新增
add() {
let car = { 'id': this.id, 'name': this.name, 'ctime': new Date() }
this.list.push(car)
this.name = this.id = ''
},
// 删除
del(id) {
// some()是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true
this.list.some((item, index) => {
if (item.id === id) {
this.list.splice(index, 1)
return true
}
})
// findIndex方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置
// let index = this.list.findIndex(item => {
// if (item.id == id)
// return true
// })
// this.list.splice(index, 1)
}
}
});
Vue.config.devtools = true;
</script>
</body>
</html>
本作品采用《CC 协议》,转载必须注明作者和本文链接