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


免責聲明!

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



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