项目中遇到这么个需求,由于选项数据量过大,采用远程搜索的方式,相当于没有初始的下拉数组options选项数组,保存时需要传给后端id和userName两个字段。
此时我的value绑定的为item(选项对象),注意下列例子为 多选 情况
- 绑定值为对象
- label绑定值为userName
// item实例
item = {
userId: '1',
userName: 'user004'
}
<el-select
v-model="selectedList" //将选中的值绑定到集合selectedList中
multiple
ref="selectDom"
placeholder="请选择">
<el-option
v-for="item in options"
:key="item.userId"
:label="item.userName"
:value="item">
</el-option>
</el-select>
当我再次编辑需要回显时,我拿到的数据后如何去让组件正确回显呢?当我把拿到的数据以对象数组的形式赋值给v-model绑定的变量中,此时会发现:组件的tag上并无label显示,显示为空,如图所示
下面提供两个方法
1.给下拉选项options赋值
//selectedList 接收后端返回来的选中集合
this.options.push(...selectedList )
由于下拉选项options中没有值所以无法正确显示,那么第一种思路我们就把options中添加数据,使其能找到对应的选中项从而正确显示
但是这个方法有个缺陷,
在select组件获焦但未远程搜索时,下拉选项会有选项出现,就是我们刚刚添加的两项,下面再提供一种方法
2.看源码理解组件是如何渲染的
先前使用给$res.selectDom.selected赋值
$res.selectDom.selected.push({
currentLabel: **,
currentValue: {
userId: **,
userName: **
},
value: {
userId: **,
userName: **
}
})
,但发现最后selected中各项的currentLabel并未被赋值,猜想组件渲染过程中有过程将此部分重新赋值,方法失败
后找到element的select.vue发现
设置选中的方法中,多选时(this.multiple == true时),通过getOption方法处理value值后返回this.selected = result
而在getOption方法中看到有个很关键的地方:this.cachedOptions,通过遍历并比对找到对应的option并return,猜想this.cachedOptions就是当前组件后台隐匿储存的下拉选项集合,那我们可以通过在这个集合中把我们需要显示的选项添加进去,即可通过组件的setSelected方法去让label渲染到组件上,
所以最终解决方法为:在拿到数据后执行下面代码
// 注意 我的例子中label绑定的为userName, value绑定的为item;
// :label="item.userName" :value="item"
// selectedList为后端返回的选中的回显数据
// 这段代码根据你们绑定的字段进行修改
selectedList.forEach(item = > {
this.$refs.selectDom.cachedOptions.push({
currentLabel: item.userName,
currentValue: {
userId: item.userId,
userName: item.userName
},
label: item.userName,
value: {
userId: item.userId,
userName: item.userName
},
})
})
循环向cachedOptions中添加选项,这样就可以了