vue+element 实现下拉框共享options

背景

用户的需求总是多样的,这不用户想做个下拉连选,每选一个基金,下方表格多一行,选择对应的重要性,任务;
在这里插入图片描述

问题

其他都好弄,任务是远程搜索,选择人的单选下拉,如果每个下拉都对应独立的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

椰汁菠萝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值