Vue使用ElementUi进行模糊搜索
文章目錄
- ElementUi進(jìn)行模糊搜索
- 前言:
- 官方函數(shù)說明
- 函數(shù)分析
- 解決方案
- python引申
ElementUi進(jìn)行模糊搜索
前言:
在ElementUi中,在帶輸入建議的輸入框中進(jìn)行搜索,發(fā)現(xiàn)只能通過首端匹配,如果輸入的是非首字,將無法搜索。
首字搜索
輸入豪或者豪大大,可搜索到豪大大香雞…內(nèi)容
非首字搜索
輸入雞,啥也搜不到
官方函數(shù)說明
autocomplete 是一個(gè)可帶輸入建議的輸入框組件,fetch-suggestions 是一個(gè)返回輸入建議的方法屬性,如 querySearch(queryString, cb),在該方法中你可以在你的輸入建議數(shù)據(jù)準(zhǔn)備好時(shí)通過 cb(data) 返回到 autocomplete 組件中。
主要靠的就是如下方法:
querySearch(queryString, cb) {var restaurants = this.restaurants;var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;// 調(diào)用 callback 返回建議列表的數(shù)據(jù)cb(results);},createFilter(queryString) {return (restaurant) => {return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);};},函數(shù)分析
略微分析一波,額,看不太懂。
仔細(xì)分析一波,找到核心突破口,createFilter,中文意思不就是創(chuàng)建過濾嘛,那好辦了,直接看這個(gè)函數(shù)里面的內(nèi)容。
return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);理性拆解分析一波
toLowerCase() //用于把字符串轉(zhuǎn)換為小寫。 indexOf() //返回某個(gè)指定的字符串值在字符串中首次出現(xiàn)的位置。如果要檢索的字符串值沒有出現(xiàn),則該方法返回 -1。好家伙,原來在這里,indexof表示首次出現(xiàn)的位置,那么三個(gè)等于號(hào)加個(gè)0是什么。
粗略理解一波,就是必須要找到這個(gè)下標(biāo)且在首位。這個(gè)零就是表示所找到的這個(gè)index下標(biāo)必須為0;
而我們需要干嘛?我們需要不管這個(gè)字在不在首位,只要在這個(gè)字符串里面,那就算找到,這就是我們的模糊搜索的要點(diǎn)。
既然如此,沒找到是-1,那么讓它大于-1不就可以了?
解決方案
將createFilter方法中的返回方法改成如下,>-1
return (restaurant.host.toLowerCase().indexOf(queryString.toLowerCase()) > -1);python引申
畢竟,咱做測(cè)試的,大部分用的python會(huì)多億些,那么看js代碼可能會(huì)像我一樣云里霧里,扒出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.*/這是不是讓你聯(lián)想到了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,說的傻子都能看懂了。
找到了返回最開始找到的下標(biāo)值,沒找到返回-1嘛這不是。
來個(gè)小案列鞏固一下。
all = 'text_xiaozaixt' part = 'xt' notin = 'm'print(all.find(part)) # 2 表示首次出現(xiàn)的位置下標(biāo)為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里面") # ------------運(yùn)行結(jié)果---------------- xt找到了 m不在name里面總結(jié)
以上是生活随笔為你收集整理的Vue使用ElementUi进行模糊搜索的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网易云歌词解析(配合audio标签实现本
- 下一篇: Vue项目中---文本框中加入simdi