1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Document</title>
9 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
10 </head>
11
12 <body>
13 <div id="app">
14 id: <input type="text" v-model="id">
15 name: <input type="text" v-model="name">
16 <button @click='add'>添加</button>
17 请输入关键字: <input type="text" v-model="keywords"><button @change='search'>检索</button>
18 <table>
19 <tr v-for="(item,index) in search()">
20 <td>{{item.id}}</td>
21 <td>{{item.name}}</td>
22 <td><a href="#" @click.prevent='del(item.id)'>删除</a></td>
23 </tr>
24 </table>
25 </div>
26 <script>
27 var vm = new Vue({
28 el: '#app',
29 data: {
30 id: '',
31 name: '',
32 keywords: '',
33 list: [{
34 id: 1,
35 name: '宝马',
36
37 },
38 {
39 id: 2,
40 name: '凯迪拉克',
41
42 },
43 {
44 id: 3,
45 name: '白龙马',
46
47 },
48 {
49 id: 4,
50 name: '奥迪',
51
52 }
53 ]
54 },
55 methods: {
56 add() {
57 this.list.push({
58 id: this.id,
59 name: this.name
60 });
61 this.id = '';
62 this.name = '';
63 },
64 del(id) {
65 const index = this.list.findIndex(function (item, i, arr) {
66 return item.id == id;
67 });
68 this.list.splice(index, 1);
69 },
70 // search() {
71 // let arr = [];
72 // for (index in this.list) {
73 // // if (this.list[index].name.indexOf(this.keywords) != -1) {
74 // // arr.push(this.list[index]);
75 // // }
76 // //另一种更简洁的方法
77 // if (this.list[index].name.includes(this.keywords)) {
78 // arr.push(this.list[index]);
79 // }
80 // }
81 // return arr;
82 // }
83
84 //简易版本
85 // search() {
86 // const arr = this.list.filter((item) => {
87 // return item.name.includes(this.keywords);
88 // });
89 // return arr;
90 // }
91 //还可以再简化,一行搞定
92 search() {
93 return this.list.filter(item => item.name.includes(this.keywords));
94 }
95 }
96 });
97 </script>
98 </body>
99
100 </html>