原理:
// 根據id得到下標
// 默認去遍歷list集合,將集合中的每個元素傳入到function的item里,
var index = this.list.findIndex(function(item){
//根據item中的id屬性來判斷這個item是否是上面id中
//對應的數據,如果是返回一個true ,否返回false,繼續下面的一條數據的遍歷,以此類推
return item.id ==id; //如果返回true,那么findIndex方法會將這個item對應的id返回到外面接受
});
實例:
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 <style>
10 #app {
11 width: 600px;
12 margin: 10px auto;
13 }
14
15 .tb {
16 border-collapse: collapse;
17 width: 100%;
18 }
19
20 .tb th {
21 background-color: #0094ff;
22 color: white;
23 }
24
25 .tb td,
26 .tb th {
27 padding: 5px;
28 border: 1px solid black;
29 text-align: center;
30 }
31
32 .add {
33 padding: 5px;
34 border: 1px solid black;
35 margin-bottom: 10px;
36 }
37 </style>
38 </head>
39
40 <body>
41 <div id="app">
42 <div class="add">
43 編號: <input type="text" v-model="id">品牌名稱: <input v-model="name" type="text">
44 <button @click="add">添加</button>
45 </div>
46 <div class="add">品牌名稱:<input type="text"></div>
47 <div>
48 <table class="tb">
49 <tr>
50 <th>編號</th>
51 <th>品牌名稱</th>
52 <th>創立時間</th>
53 <th>操作</th>
54 </tr>
55 <tr v-if="list.length <= 0">
56 <td colspan="4">沒有品牌數據</td>
57 </tr>
58 <!--加入: key="index" 時候必須把所有參數寫完整 -->
59 <tr v-for="(item,key,index) in list" :key="index">
60 <td>{{item.id}}</td>
61 <td>{{item.name}}</td>
62 <td>{{item.ctime}}</td>
63 <!-- 使用vue來注冊事件時,我們在dom元素中是看不到的 -->
64 <td><a href="javascript:void(0)" @click="del(item.id)">刪除</a></td>
65 </tr>
66 </table>
67 </div>
68
69 </div>
70 </body>
71
72 </html>
73 <script src="vue2.4.4.js"></script>
74 <script>
75 var vm = new Vue({
76 el: "#app",
77 data: {
78 id: 0,
79 name: '',
80 list: [
81 { "id": 1, "name": "it", "ctime": Date() },
82 { "id": 2, "name": "白龍", "ctime": Date() }
83 ]
84 },
85 methods: {
86 add: function () {
87 //將id和namepush到list數組中
88 this.list.push({ "id": this.id, "name": this.name, "ctime": Date() });
89 },
90 del:function(id) {
91
92 // 根據id得到下標
93 // 默認去遍歷list集合,將集合中的每個元素傳入到function的item里,
94 var index = this.list.findIndex(function(item){
95 //根據item中的id屬性來判斷這個item是否是上面id中
96 //對應的數據,如果是返回一個true ,否返回false,繼續下面的一條數據的遍歷,以此類推
97 return item.id ==id; //如果返回true,那么findIndex方法會將這個item對應的id返回到外面接受
98 });
99 // 根據下標在list集合中將對應的數據刪除
100 // splice(開始刪除的下標,刪除的長度)
101 this.list.splice(index,1);
102 }
103 }
104 });
105
106 </script>