背景
用户的需求总是多样的,这不用户想做个下拉连选,每选一个基金,下方表格多一行,选择对应的重要性,任务;
问题
其他都好弄,任务是远程搜索,选择人的单选下拉,如果每个下拉都对应独立的options,那真是维护灾难,本身这也是动态的,而且感觉也完全没必要;尝试所有任务下拉使用同一个options对象;
核心代码
- template
<el-table-column label="任务B角">
<template slot-scope="scope">
<el-select
v-model="scope.row.taskB"
placeholder="请选择"
filterable
remote
clearable
:remote-method="queryUsers"
@change="userSelectChange($event,scope.row.investFundId,'taskB')"
>
<el-option
v-for="item in userOptions"
:key="item.userId"
:label="item.userName"
:value="item.userId"
/>
</el-select>
</template>
</el-table-column>
- js
<script>
export default {
data () {
return {
userOptions: [] // / 共享options
}
},
watch: {
value: {
handler (newVal) {
if (newVal != null && newVal.length > 0) {
this.initPage(newVal)
}
},
deep: true
}
},
methods: {
userSelectChange (userId, investId, key) {
this.$nextTick(() => {
this.userOptions = this.mergeUserArrays(this.userOptions, [])
})
},
queryUsers (keyword) {
const param = new URLSearchParams()
param.append('key', keyword || '')
getAllCreateHumans(param).then(res => {
this.userOptions = res?.data ?? []
})
},
mergeUserArrays (arr1, arr2) {
const map = new Map();
// 遍历第二个数组(后合并的数组,优先保留)
[...arr2 ?? [], ...arr1 ?? []].forEach(user => {
map.set(user.userId, user) // 后设置的会覆盖前面的
})
return Array.from(map.values())
}
}
}
</script>
- element的select,在搜索时,下拉展示的是接口返回列表,感觉并没有真正修改options,当选中后,会把选中项添加入options中;
- 当有多个下拉选择同一个用户时,options中会出现重复项,这就需要
去重
了- 但
去重
时机比较重要,要在select添加完选中项之后,否则去重代码没有效果;因此代码中使用了$nextTick