Vue使用ElementUi进行模糊搜索
文章目錄
- ElementUi進行模糊搜索
- 前言:
- 官方函數說明
- 函數分析
- 解決方案
- python引申
ElementUi進行模糊搜索
前言:
在ElementUi中,在帶輸入建議的輸入框中進行搜索,發現只能通過首端匹配,如果輸入的是非首字,將無法搜索。
首字搜索
輸入豪或者豪大大,可搜索到豪大大香雞…內容
非首字搜索
輸入雞,啥也搜不到
官方函數說明
autocomplete 是一個可帶輸入建議的輸入框組件,fetch-suggestions 是一個返回輸入建議的方法屬性,如 querySearch(queryString, cb),在該方法中你可以在你的輸入建議數據準備好時通過 cb(data) 返回到 autocomplete 組件中。
主要靠的就是如下方法:
querySearch(queryString, cb) {var restaurants = this.restaurants;var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;// 調用 callback 返回建議列表的數據cb(results);},createFilter(queryString) {return (restaurant) => {return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);};},函數分析
略微分析一波,額,看不太懂。
仔細分析一波,找到核心突破口,createFilter,中文意思不就是創建過濾嘛,那好辦了,直接看這個函數里面的內容。
return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);理性拆解分析一波
toLowerCase() //用于把字符串轉換為小寫。 indexOf() //返回某個指定的字符串值在字符串中首次出現的位置。如果要檢索的字符串值沒有出現,則該方法返回 -1。好家伙,原來在這里,indexof表示首次出現的位置,那么三個等于號加個0是什么。
粗略理解一波,就是必須要找到這個下標且在首位。這個零就是表示所找到的這個index下標必須為0;
而我們需要干嘛?我們需要不管這個字在不在首位,只要在這個字符串里面,那就算找到,這就是我們的模糊搜索的要點。
既然如此,沒找到是-1,那么讓它大于-1不就可以了?
解決方案
將createFilter方法中的返回方法改成如下,>-1
return (restaurant.host.toLowerCase().indexOf(queryString.toLowerCase()) > -1);python引申
畢竟,咱做測試的,大部分用的python會多億些,那么看js代碼可能會像我一樣云里霧里,扒出js的indexOf源碼瞅一眼。
indexOf(searchString: string, position?: number): number;/*** Returns the last occurrence of a substring in the string.* @param searchString The substring to search for.* @param position The index at which to begin searching. If omitted, the search begins at the end of the string.*/這是不是讓你聯想到了python里面的find方法?
那讓我們看一下find的源碼
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.find(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0不愧是python,說的傻子都能看懂了。
找到了返回最開始找到的下標值,沒找到返回-1嘛這不是。
來個小案列鞏固一下。
all = 'text_xiaozaixt' part = 'xt' notin = 'm'print(all.find(part)) # 2 表示首次出現的位置下標為2 print(all.find(notin)) # -1 print("-----------------") # python indexOf if (all.find(part) > -1):print(f"{part}找到了") else:print(f"{part}不在name里面")if (all.find(notin) > -1):print(f"{notin}找到了") else:print(f"{notin}不在name里面") # ------------運行結果---------------- xt找到了 m不在name里面總結
以上是生活随笔為你收集整理的Vue使用ElementUi进行模糊搜索的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网易云歌词解析(配合audio标签实现本
- 下一篇: (一)云计算技术学习--基础概念