背景提要
最近项目有一个需求,在选择地址时,可供下拉选择的地址不全,用户可以手动输入没有枚举的地址,并且可将这次输入地址增加到字典中。
1、找到a-select组件,在此基础上改造
在antd组件中,与之功能最接近的UI组件是组件,因此在此组件基础上进行修改,因为带搜索框的选择器可以输入内容,因此增加show-search,filter-option,@search=“handleSearch” 等属性和事件,当用户输入内容时则触发查询事件handleSearch,在查询事件中讲输入值赋值给选择器的value值。
详细代码片段如下:
// An highlighted block
<template>
<a-select
show-search
:value="selectValue"
optionLabelProp='children'
:autoClearSearchValue="false"
style="width: 100%"
placeholder="请选择类型"
:default-active-first-option="false"
:filter-option="true"
:not-found-content="null"
@search="handleSearch"
@blur="handleBlur"
@change="handleChange"
>
<a-select-option v-for="(item,index) in selectData" :key="index" :value="item.value">
{{ item.label }}
</a-select-option>
</a-select>
</template>
<script>
export default {
props:{
selectData:{
type:Array,
default:()=>[]
},
value: {
type: String,
required: false
}
},
data () {
return {
selectValue:''
}
},
watch: {
value (val) {
if (!val) {
this.selectValue = '';
} else {
this.selectValue = this.value;
}
}
},
methods:{
handleSearch (value) {
this.handleChange(value);
},
handleChange (value) {
console.log(value)
this.selectValue = value;
},
handleBlur() {
this.selectValue=value;
this.$emit('change',selectValue )
}
}
}
2、 父组件引入封装后的edit-select组件
外部引用该组件时,可以使用v-model=“”的方式将变量传入(与props的value绑定),当外部的变量传入组件,使用失去焦点触发事件,将value值赋值给选择器,从而形成双向绑定。
外部引用的代码片段如下:
<a-form-item label="区域2" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
<edit-select :selectData="selectData" v-model="area"/>
</a-form-item>