一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第8天,点击查看活动详情。
最近在项目开发中发现ant-design-vue中的下拉框在设置初始值的时候有下面一个问题:
直接 default-value="aa"
可以,但是动态绑定值就不行
了 :default-value="code"
bug: select值是异步加载,需要默认选中第一项,但是没有选中
方案1:添加一个key, 值为你所需要的 defaultValue
解决方案: 在Select 组件中添加一个key, 值为你所需要的 defaultValue
<a-select
label-in-value
style="width: 100%"
:default-value="{key:model.locationCode}"
:key="model.locationCode"
@change="handleChangePositionCode"
>
<a-select-option :value="item.code" v-for="(item, idx) in positionList" :key="idx">
{{item.code}}
</a-select-option>
</a-select>
下拉搜索
<a-select
show-search
label-in-value
style="width: 100%"
:default-value="{ key: model.supplierCode }"
:key="model.supplierCode"
:filter-option="false"
:not-found-content="fetching ? undefined : null"
@search="fetchCode"
@change="handleChangeCode"
>
<a-spin v-if="fetching" slot="notFoundContent" size="small" />
<a-select-option :value="item.code" v-for="(item, idx) in supplierList" :key="idx"
>{{ item.code }} _ {{ item.name }}</a-select-option
>
</a-select>
async edit(record) {
await this.fetchCode(record.supplierCode)
this.model = Object.assign({}, record)
this.visible = true
},
// 下拉选择框赋值
fetchCode(val) {
if (val === '') return
this.fetching = true
getAction('/basedata/baseSupplier/list', { superQueryParams: encodeURI(JSON.stringify([
{
"rule":"like", //查询规则
"type":"string",
"dictCode":"",
"val": val, //值
"field":"code" //模糊查询字段
}])) }).then(data => {
this.supplierList = data.result.records
this.fetching = false
})
// getAction('/basedata/baseSupplier/list', { code: val }).then(data => {
// this.supplierList = data.result.records
// this.fetching = false
// })
}
方案2:在a-select
中使用v-model
即可,在mounted里面设置默认值。
<template>
<div>
<a-select v-model="cardAttr" placeholder='请选择账户类型' style='width: 230px' @change='handleAccountTypeChange'>
<a-select-option :value='item.id' v-for="(item,index) in cardType" :key='index'>
{{item.name}}
</a-select-option>
</a-select>
</div>
</template>
<script>
export default {
data() {
return {
cardType:[{'id':"1",name:'私人账户'},{'id':"2",name:'公司账户'}],
cardAttr:null,
};
},
methods:{
handleAccountTypeChange(e){
console.log('账户类型',e);
this.cardAttr = e;
},
},
mounted() {
this.cardAttr = '2';
}
};
</script>
<style>
</style>
getFieldDecorator
用于和表单进行双向绑定,单文件 template 可以使用指令v-decorator进行绑定,
设置初始值代码也可以写成以下形式:
<a-form :form="form">
<a-form-item label="入库类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
<a-select
v-decorator="['source', { initialValue: '4' } ,validatorRules.source]"
@change="changeType"
placeholder="请选择入库类型"
:disabled="typeDisabled"
>
<a-select-option value="4" > 退料入库 </a-select-option>
<a-select-option value="5"> 退货入库 </a-select-option>
</a-select>
</a-form-item>
</form>