背景
用戶的需求總是多樣的,這不用戶想做個下拉連選,每選一個基金,下方表格多一行,選擇對應的重要性,任務;
問題
其他都好弄,任務是遠程搜索,選擇人的單選下拉,如果每個下拉都對應獨立的options,那真是維護災難,本身這也是動態的,而且感覺也完全沒必要;嘗試所有任務下拉使用同一個options對象;
核心代碼
- template
<el-table-column label="任務B角"><template slot-scope="scope"><el-selectv-model="scope.row.taskB"placeholder="請選擇"filterableremoteclearable:remote-method="queryUsers"@change="userSelectChange($event,scope.row.investFundId,'taskB')"><el-optionv-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