vue实现多个下拉去重

我们先来看一个图:
演示去重
可以看到,在添加下拉之后,之前选过的选项不会出现在下拉里面了。
线上地址:线上地址
整个实现过程是用vue实现的,总体来说蛮简单,如果用jQuery实现就会复杂得多。
下面我们来看看vue-devtool里面的数据:
数据结果
从数据层面,容易看出,整个下拉数据是来自selectMap,通过比较selectItemList来判断是否已经选中,选中的选项不显示。通过求和money计算出total.
下面看一下具体实现:

<h5>选择款项,并填写费用</h5>
    <div class="select-list" v-for="(item,index) in selectItemList" :key="index">
      <el-select v-model="item.id" placeholder="选择款项">
        <el-option v-for="(val,key) in selectMap" v-show="isSelect(parseInt(key),item.id)" :value="parseInt(key)" :key="key" :label="val"></el-option>
      </el-select>
      <el-input placeholder="请输入费用" v-model="item.money" type="number" class="money"></el-input>
      <el-button type="info" icon="el-icon-circle-plus-outline" circle @click="add" v-show="selectData.length > selectItemList.length"></el-button>
      <el-button type="info" icon="el-icon-remove-outline" circle @click="reduce(index)" v-show="selectItemList.length > 1"></el-button>
    </div>
    <h5 class="total">{{`总费用:${total}元`}}</h5>

需要用到的函数:

//控制选项是否显示
isSelect(id,currentId){
        if(currentId === id){
          return true
        }
        for(let i in this.selectItemList){
          if(this.selectItemList[i].id === id){
            return false
          }
        }
        return true
      }
//新增
add(){
        this.selectItemList.push({id:'',money:0})
      }
//删除
reduce(index){
        this.selectItemList.splice(index,1)
      }
//求和
total(){
        let total = 0
        this.selectItemList.forEach(row => {
          if(row.id){
            total += parseInt(row.money) || 0
          }
        })
        return total
      }

整体实现是蛮简单的,之前用jQuery实现过一次,感觉超级麻烦,用选择器控制dome是否显示,判断一大堆,还容易搞错了,没一步都要绑定change事件,来让view与model保持一致。使用vue实现就完成不用担心这些问题了,整个实现过程没有绑定一个change
所有的代码都能在GitHub下载:下载
想看更多文章,可以关注我的个人公众号:
公众号

原文地址:https://www.cnblogs.com/zhujieblog/p/12816866.html