我們先來看一個圖:


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