vue學習(十四) 條件搜索框動態查詢表中數據 數組的新方法

//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>
相關文章
相關標籤/搜索