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
方法,我們將searchTex
t變量作為正則表達式的檢測標准:
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函數迭代一個數組,然后根據傳入的函數篩選合適的元素並且返回一個全新的數組
搜索空:
搜索“瓜“: