Loading

vue实现的前端模糊匹配搜索

vue实现的前端模糊匹配搜索

可以借助js自带的filter方法和正则表达式来筛选我们需要的元素

首先构建html框架:

<div id="app">
    <div class="wrapper">
      <input type="text" v-model="searchText"><button @click="submit">搜索</button>
    </div>
    <table>
      <thead>
        <th>名称</th>
        <th>价格</th>
        <th>备注</th>
      </thead>
      <tbody>
        <tr v-for="(item,index) in data" :key="index">
          <td>{{item.label}}</td>
          <td>¥{{item.price}}</td>
          <td>{{item.desc}}</td>
        </tr>
      </tbody>
    </table>
  </div>

用户输入的内容动态绑定在变量searchText上,用户点击搜索触发submit方法,我们将searchText变量作为正则表达式的检测标准:

submit() {
      let text = this.searchText
      let reg = new RegExp(text) //声明正则变量
      this.data = this.tableData.filter(item => reg.test(item.label)) //返回
    }

这里使用了data变量用于存储搜索后的结果(以及绑定到表格上渲染),tableData存储表格的原始数据,目的是当用户输入空格时可以还原所有数据,this.tableData.filter(item => reg.test(item.label)) 是简写用法,完整为:

let func = function (item) {
        if (reg.test(item.label)) { //检测通过
          return item
        }
      }
      this.data = this.tableData.filter(func)

filter函数迭代一个数组,然后根据传入的函数筛选合适的元素并且返回一个全新的数组

搜索空:

image-20210614111515130

搜索“瓜“:

image-20210614111606474

posted @ 2021-06-14 11:17  Maji-May  阅读(2750)  评论(0编辑  收藏  举报