//html <div id="app">
<label>
名稱搜索關鍵字:
<input type="text" clasa="form-control" v-model="keywords">
</label> <table class="table table-bordeered table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
//之前,v-for中的數據,都是直接從data上的list中直接渲染過來的
//現在,自定義了一個search方法,同時,把所有的關鍵字,通過傳參的形式,傳遞給search方法
//在search方法內部,通過執行for循環,把所有符合搜索關鍵字的數據,保存到一個新數組中返回
//
<tr v-for="item in search(keyword)" :key="item.id">// search 是一個方法
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table> </div> //script <script> var vm = new Vue({ el:'app', data:{ id:'', name:'',
keyword:'', list:[ {id:1, name:'驚鯢'}, {id:2, name:'掩日'}, {id:2, name:'黑白玄翦'} ] }, methods:{//methods中定義了當前vue實例中所有可用的方法 search(keywords){//根據關鍵字進行數據搜索 var newList = []
this.list.forEach(item=>{
//indexOf()方法可以判斷字符串中是否包含寫字符串
if(item.name.indexOf(keywords) !=-1){
newList.push(item)
}
})
return newList }
//下面的方法也可以
//forEach some filter findIndex 這些都是數組的新方法
//都會對數組中的每一項進行遍歷,執行相關的操作
search(keywords){
return this.list.filter(item=>{
//ES6中為字符串提供了一個新方法,叫做 string.prototype.includes('要包含的字符串')
//如果包含則返回true 否則返回false
if(item.name.includes(keywords)){
return item
}
})
} } }) </script>