鍍金池/ 問答/HTML/ ElementUI Select組件 filter-method問題

ElementUI Select組件 filter-method問題

有一個(gè)需求是這樣的,Select選城市的時(shí)候需要模糊搜索,不僅要支持中文,而且要支持拼音,縮寫等等,后端會(huì)給我相應(yīng)的字段,但是我發(fā)現(xiàn)使用filter-method傳入函數(shù)實(shí)現(xiàn)的這種辦法會(huì)讓自己寫很多多余的代碼,直接上例子

<el-select v-model="value8" :filter-method="handleCityFilter" filterable placeholder="請(qǐng)選擇">
    <el-option
      v-for="item in filterOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>

handleCityFilter (val) {
   // filter balabalbalb....
}

這種方式還要緩存一次options,每次在過濾函數(shù)里把緩存的options過濾然后賦值給filterOptions,感覺會(huì)非常麻煩,也不優(yōu)雅,理想情況下應(yīng)該是在handleCityFilter這個(gè)函數(shù)里面把事情都辦了

<el-select v-model="value8" filterable placeholder="請(qǐng)選擇">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>

官方這個(gè)例子只是傳入了options沒做緩存,但是也可以模糊搜索,于是想去源碼里看看怎么實(shí)現(xiàn)的

// select.vue
this.broadcast('ElOption', 'queryChange', val);

// option.vue
      queryChange(query) {
        // query 里如果有正則中的特殊字符,需要先將這些字符轉(zhuǎn)義
        let parsedQuery = String(query).replace(/(\^|\(|\)|\[|\]|\$|\*|\+|\.|\?|\\|\{|\}|\|)/g, '\\$1');
        this.visible = new RegExp(parsedQuery, 'i').test(this.currentLabel) || this.created;
        if (!this.visible) {
          this.select.filteredOptionsCount--;
        }
      }

最終鎖定在這里,發(fā)現(xiàn)是將options組建正則隱藏,那么通過filterMethod必然無法辦到這個(gè)事情。。。各位大神們對(duì)于這種需求有什么更好的解決方案嗎

回答
編輯回答
孤毒

發(fā)現(xiàn)可以將綁定的label設(shè)置為prefix + pinyin,但是使用鍵盤選中的時(shí)候又會(huì)出問題,選中的而不是slot的option而是設(shè)置的label,看來也不是一個(gè)優(yōu)雅的解決方案,求大佬~~

2018年3月24日 12:34