我們先來(lái)看一個(gè)圖:
演示去重
可以看到,在添加下拉之后,之前選過(guò)的選項(xiàng)不會(huì)出現(xiàn)在下拉里面了。
整個(gè)實(shí)現(xiàn)過(guò)程是用vue實(shí)現(xiàn)的,總體來(lái)說(shuō)蠻簡(jiǎn)單,如果用jQuery實(shí)現(xiàn)就會(huì)復(fù)雜得多。
下面我們來(lái)看看vue-devtool里面的數(shù)據(jù):
數(shù)據(jù)結(jié)果
從數(shù)據(jù)層面,容易看出,整個(gè)下拉數(shù)據(jù)是來(lái)自
selectMap,通過(guò)比較selectItemList來(lái)判斷是否已經(jīng)選中,選中的選項(xiàng)不顯示。通過(guò)求和money計(jì)算出total.下面看一下具體實(shí)現(xiàn):
<h5>選擇款項(xiàng),并填寫(xiě)費(fèi)用</h5>
<div class="select-list" v-for="(item,index) in selectItemList" :key="index">
<el-select v-model="item.id" placeholder="選擇款項(xiàng)">
<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="請(qǐng)輸入費(fèi)用" 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">{{`總費(fèi)用:${total}元`}}</h5>
需要用到的函數(shù):
//控制選項(xiàng)是否顯示
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
}
整體實(shí)現(xiàn)是蠻簡(jiǎn)單的,之前用jQuery實(shí)現(xiàn)過(guò)一次,感覺(jué)超級(jí)麻煩,用選擇器控制dome是否顯示,判斷一大堆,還容易搞錯(cuò)了,沒(méi)一步都要綁定change事件,來(lái)讓view與model保持一致。使用vue實(shí)現(xiàn)就完成不用擔(dān)心這些問(wèn)題了,整個(gè)實(shí)現(xiàn)過(guò)程沒(méi)有綁定一個(gè)change。