品牌管理案例
(1)bootstrip快速布局
<div class="app"> <div class="panel panel-primary"> <div class="panel-heading"> <h2>品牌管理</h2> </div> <div class="panel-body form-inline"> <label for="">id:<input type="text" class="form-control" v-model="id"></label> <label for="">品牌名稱:<input type="text" class="form-control" v-model="name"></label> <input type="button" value="添加" class="btn btn-primary" @click="add"> </div> </div> <table class="table table-bordered table-hover"> <thead> <tr> <th>id</th> <th>品牌名稱</th> <th>添加時間</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="item in arr" :key="item.id"> <td v-text="item.id"></td> <td v-text="item.name"></td> <td v-text="item.time"></td> <td><a href="" @click.prevent="del(item.id)">刪除</a></td> </tr> </tbody> </table> </div>
(2)業務邏輯的實現
<script> var vm= new Vue({ //創建vue實例 el:'.app', data:{ arr:[ {'id':1,'name':'iPhone','time':new Date()}, {'id':2,'name':'華為','time':new Date()}, {'id':3,'name':'OPPO','time':new Date()} ], //創建一些初始數據與格式 id:'', name:'' }, methods:{ add(){ this.arr.push({'id':this.id,'name':this.name,'time':new Date()}); this.id=this.name=''; },//add方法實現列表的輸入功能 del(id){ var index=this.arr.findIndex(item => { if(item.id==id) { return true; } }) this.arr.splice(index,1) //findIndex方法查找索引實現列表的刪除功能 // this.arr.some((item,i) => { // if (item.id===id) { // this.arr.splice(i,1) // return true; // } // })//some方法查找索引實現列表的刪除功能 } } }) </script> </body> </html>
(3)兩種查找索引的方式
在實現刪除列表項的功能時,使用splice(從何開始,刪除幾個,插入項)方法,因此從何開始(index)需要我們把它揪出來。
第一種方法使用some()函數遍歷數組,通過回調函數設置判斷條件,當條件成立即索引對應成立時執行刪除操作,終止循環。
第二種方法使用findIndex()方法直接獲取索引,同樣是在回調函數中進行判斷,當條件成立(item.id==id)時,拿到索引,使用splice()刪除列表項。