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下載:下載
想看更多文章,可以關注我的個人公衆號:
公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章