<!--new 的 vue 實例會控制這個元素中的所有內容,也是MVVM中的 V --> <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>Id: <input type="text" class="form-control" v-model="id"/></label> <label>Name: <input type="text" class="form-control" v-model="name"/></label> <input type="button" value="添加" class="btn btn-primary" @click="add"/> <label>搜索關鍵字: <input type="text" class="form-control" v-model="keywords"/></label> </div> </div> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Ctime</th> <th>Operation</th> </tr> </thead> <tbody> <!--自定義 search 方法,把關鍵字通過傳參的形式,傳遞給 search方法,在 search 方法內部,通過 執行 for循環,把所有符合 搜索關鍵字的數據,保存到一個新數據中,返回 --> <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> //創建一個vue的實例,也是MVVM中的 VM調度者,里面可傳配置對象 var vm = new Vue({ el:"#app", //data指MVVM中的 M ,用來存 el 中用的數據 data:{ id:"", name:"", keywords:"", list:[ {id:1, name:'名字1', ctime:new Date()}, {id:2, name:'名字2', ctime:new Date()} ] }, methods:{ add:function(){ var abc = {id:this.id, name:this.name, ctime:new Date()} this.list.push(abc); this.id = this.name = "" }, // 刪除事件邏輯: // 1.刪除的時候一般是根據 id 來進行刪除的 // 2.給個點擊事件,取消默認事件,因為要通過id來刪,所以將id傳個參 @click.prevent="del(item.id)" // 3.定義 del 的方法(函數,點擊事件) // 4.函數中 傳參id,根據id刪除數據 // 5.分析: // i:根據id,找到當前的索引 // ii:找到索引了,根據 數組的 splice 方法進行刪除 // 6.注意: forEach some filter findIndex 這些都屬於數組的新方法 // forEach : 沒有辦法終止 // some : 通過 return:true 可以終止 // filter : 過濾,符合條件的 // findIndex : 找到數組對應的索引,專門查找索引 // 7.之所以用到some ,是因為找到要刪除的 id后,就終止了循環 // some和findIndex的區別:some方法中可以做任何事情,但是findIndex是專門用來查索引的 del:function(id){ // 一種寫法: // this.list.some((item,i)=>{ // if(item.id == id){ // .splice(2,3) 從索引為 i(或者2) 開始,刪除 1(或者3) 個 // this.list.splice(i,1) // 終止循環 // return true; // } // }); // 另一種寫法: var index = this.list.findIndex(item =>{ if(item.id == id){ return true; } }); this.list.splice(index,1) }, search:function(keywords){ var newList = [] this.list.forEach(item=>{ if(item.name.indexOf(keywords) != -1){ newList.push(item) } }) return newList; // return this.list.filter(item =>{ // if(item.name.indexOf(keywords) != -1) // ES6中,為字符串提供了一個新的方法,String.prototype.includes('要包含的字符串'),如果包含,則返回 true ,否則返回 false // if(item.name.includes(keywords)){ // return item // } // }) } } }) </script>