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>

猜你喜欢

转载自www.cnblogs.com/xuchao0506/p/10849694.html