项目中需要使用可下拉又可手动输入的控件,于是基于autocomplete自定了一个,下拉时获取name和id给接口,手动输入时只传name
一、创建SelectAutoComplete.vue
<template>
<div>
<a-auto-complete
v-model="record[propName]"
:placeholder="holder"
:allowClear="true"
option-label-prop="title"
:disabled="disabled"
@select="(value,title) => handleSelect(value, record, title)"
@change="e => handleChange(e, record)"
>
<template slot="dataSource">
<a-select-option v-for="item in selectSource" :key="item.value" :value="item.value" :title="item.label">
{{ item.label }}
</a-select-option>
</template>
</a-auto-complete>
</div>
</template>
<script>
export default {
name: 'SelectAutoComplete',
props: {
selectSource: {
type: Array,
required: true,
default: () => []
},
disabled: {
type: Boolean
},
holder: {
type: String,
required: true,
default: ''
},
record: {
type: Object,
required: true,
default: () => ({})
},
propName: {
type: String,
required: true
},
propId: {
type: String,
required: true
}
},
methods: {
handleSelect(value, record, option) {
record[this.propName] = option.componentOptions.propsData.title
record[this.propId] = value
},
handleChange(value, record) {
const hasValue = this.selectSource.some(item => item.label === value)
if (!hasValue) {
record[this.propName] = value
this.$set(record, this.propId, null)
}
}
}
}
</script>
<style scoped>
</style>
二、页面引用
<template>
<div>
<a-table
class="ant-table-sticky"
bordered
:columns="columns"
:dataSource="tableForm.listData"
:scroll="{ x: 800, y:350}"
:row-key="(record, index) => { return index }"
:pagination="false"
:rowSelection="rowSelection"
>
<template slot="SteelGradeName" slot-scope="text, record, index, column">
<a-form-model-item label="" :prop="`listData.${index}.SteelGradeName`" :rules="rules.SteelGradeName">
<select-auto-complete
:record="record"
:select-source="steelSource"
:disabled="disabled"
holder="材料"
prop-name="SteelGradeName"
prop-id="SteelGradeId"
></select-auto-complete>
</a-form-model-item>
</template>
</div>
</a-table>
</template>
import SelectAutoComplete from '@/components/SelectAutoComplete'
components: {
SelectAutoComplete
}