vue,多个下拉框,使用同一个数据源,实现下拉数据不被重复选择(隐藏其他选中的数据)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="addSelect">add</button>
      <div v-for="select in selectList" class="item">
        <div class="label">{{ select.label }}</div>
        <select v-model="select.value">
          <option v-for="option in getOptionList(select.value)" :value="option.value">
            {{ option.label }}
          </option>
        </select>
      </div>

      selectList: {{selectList}} <br />optionList:{{optionList}}
    </div>
    <script src="./vue3.js"></script>
    <script>
      // https://unpkg.com/vue@3/dist/vue.global.js  
      Vue.createApp({
        data() {
          return {
            optionList: [],
            selectList: [],
          };
        },
        computed: {
          // 其他下拉框已经选中的值,需要在当前下拉框不展示,遍历时,只要在这个数组里就要去掉
          selectedValue() {
            const set = new Set();
            this.selectList.forEach((item) => set.add(item.value));
            console.log('set,', set);
            return set;
          },
        },
        methods: {
          addSelect() {
            this.selectList.push({
              label: '新增下拉框',
              value: '',
            });
          },
          /**
           * 核心函数:这个函数,需要在非选择的下拉框的时候去理解
           */
          getOptionList(val) {
            console.log('888,', val);
            let res = this.optionList.filter((item) => {
              // 传过来的值!==遍历到的数据源item,并且,其他下拉框已经选中了
              if (val !== item.value && this.selectedValue.has(item.value)) return false;
              return true;
            });
            console.log('res,', res);
            return res;
          },
        },
        mounted() {
          for (let i = 0; i < 5; i++) {
            this.optionList.push({
              label: '选项' + i,
              value: 'option' + i,
            });
          }
          for (let i = 0; i < 2; i++) {
            this.selectList.push({
              label: '下拉框' + i,
              value: '',
            });
          }
        },
      }).mount('#app');
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值