1. 程式人生 > 其它 >element-UI中el-select元件使用拼音進行模糊匹配可選擇項

element-UI中el-select元件使用拼音進行模糊匹配可選擇項

技術標籤:前端拼音模糊匹配element-Uiselect元件支援首拼vue

一、安裝pinyin-match包

yarn add pinyin-match

二、引入包

import PinYinMatch from 'pinyin-match';

三、直接上程式碼

<el-select v-model="value" multiple filterable clearable :filter-method="match">
    <el-option v-for="item in optionList" :key="item.value" :label="item.label" :value="item.value"></el-option>
</el-select>
import PinYinMatch from 'pinyin-match';
export default {
    data(){
        value: [],//選中的值
        dataSource: '',//原始的集合
        optionList: '',//篩選出的結果
    },
    methods: {
        match(value){
            if(value){
                let result = [];
                this.dataSource.forEach(item=>{
                    let matchResult = PinYinMatch.match(item.label, value);
                    if(matchResult){
                        result.push(item);
                    }
                });
                this.optionList = result;
            }else{
                this.optionList = this.dataSource;
            }
        }
    },
    created(){
        this.dataSource = [
            {label: '測試1', value: 1},
            {label: '測試2', value: 2},
            {label: '測試3', value: 3},
        ];
        this.optionList= [
            {label: '測試1', value: 1},
            {label: '測試2', value: 2},
            {label: '測試3', value: 3},
        ];
    }
}

四、實現效果