Ant Design Vue - 实现 <a-select> 选择器可选择可输入字符(既可下拉选择又可自己输入)

3,898 阅读1分钟

前言

注意:只实现了 组件,其他组件可将本文作为参考。

这种需求其实不算太常见,交互不是很好。

如果您要实现如下图所示 既可下拉选择又可自己输入 选择器需求,本文可帮助到你。

0fd6ad657f24425d86114b8af173428b.gif

解决方案

    <div>
        <a-select
        v-model="result"
        :show-search="true"
        :not-found-content="null"
        :filter-option="true"
        :allowClear="true"
        style="width: 180px"
        placeholder="请选择或输入水果"
        @search="handleSearch" 
        @blur="handleBlur" 
        @change="handleChange"
        >
            <a-select-option
            v-for="(item,index) in list"
            :key="index"
            :value="item.id"
            >
                {{ item.val }}
            </a-select-option>
        </a-select>
        <!-- <h1>{{ result }}</h1> -->
    </div>
</template>
export default {
    data() {
        return {

            // 下拉列表
            list:[
                { id: '1', val: '香蕉' },
                { id: '2', val: '苹果' },
                { id: '3', val: '火龙果' },
            ],
            
            // 选择器值(最终数据)
            result: undefined,//选择下拉列表中选项后的值
        }
    },

    methods: {

        handleSearch(value){
            this.handleChange(value)
        },

        handleChange(value){
            this.result = (value != null && value != '') ? value : undefined
        },
        
        handleBlur(value){
            this.result = value;
        },
    }
}