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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM