1. 程式人生 > >vue 增刪改查

vue 增刪改查

5.1 -s label top del tony 方法 val urn

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="vue-2.5.13.min.js"></script> <style> * { padding: 0; margin: 0; position: relative; }
/* 實現任意無寬高盒子居中顯示 */ #app { position: absolute; left: 50%; top: 100px; transform: translateX(-50%); }
.box { width: 500px; height: 40px; background-color: #ccc; display: inline-block; text-align: center; line-height: 40px; border: 1px solid #aaa; box-sizing: border-box; border-bottom: none; }
.tb { width: 500px; text-align: center; border-collapse: collapse; border-color: #ccc; } </style> </head>
<body> <div id="app"> <div class="box"> <label for="id"> ID: <input type="text" id="id" v-model="id"> </label> <label for="name"> name: <input type="text" id="name" v-model="name"> </label> <input type="button" value="add" @click="addClick"> </div>
<table border="1" cellspacing="0" class="tb"> <tr v-for="item in list"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.ctime}}</td> <td> <!-- 綁定的事件是可以傳參數的,這裏傳入需要刪除的對象id --> <a href="javascript:;" @click.prevent="delClick(item.id)">del</a> </td> </tr> </table> </div>

<script> var vm = new Vue({ el: "#app", data: { id: "", name: "", list: [{ id: 1, name: ‘tony‘, ctime: new Date() }, { id: 2, name: ‘stark‘, ctime: new Date() } ] }, methods: { addClick() { // 1.獲取表單數據 // 2.組織出一個對象 // 3.將對象添加到data中(不需要重新渲染頁面) let item = { id: this.id, name: this.name, ctime: new Date() }; if ((this.id != "") && (this.name != "")) { this.list.push(item); } // 4.最後將表單清空 this.id = this.name = ""; }, delClick(id) { // 1.根據id找到索引(循環查找) // 2.調用數組的 splice方法刪除 this.list.filter((item, index) => { if (item.id == id) { this.list.splice(index, 1); return true; } });
} }
}); </script> </body> </html>

vue 增刪改查