uni-app中使用選擇框圖片來寫單選,多選,以及不可選擇
阿新 • • 發佈:2022-05-27
(check.png)(checkbox.png)(checkDisable.png)
以上三張圖是我的可選擇狀態,已選中,以及不可選擇等三種;接下來來寫幾種使用情景;具體樣式我不再細寫了,只說邏輯,需要說明image需要放在你所選擇的迴圈裡,比如如下,僅做展示,樣式可以根據需要寫
1:只支援單選,並且都可以選擇
<image v-if="orderarr.length!=0" @click="toCheck(item.id)" class="check" :src="orderarr.includes(item.id)?'/static/img/check.png':'/static/img/checkbox.png'"></image> 這裡是表示,已選中是選中狀態,未選中則是可選擇狀態 <image v-else @click="toCheck(item.id)" class="check" src="/static/img/checkbox.png"></image> 這裡是表示當前需要選擇的內容全部可選
其中的orderarr是你所選中的id陣列,includes方法是判斷當前陣列是否包含當前迴圈的id
check方法
toCheck(id){ if(this.orderarr.length==0){//判斷當前id陣列是否為空,若是為空,則直接push this.orderarr.push(id) }else{
this.orderarr=[]//由於當前邏輯是單選,直接清空再push就好了
this.orderarr.push(id)
}
console.log(this.orderarr); },
2:支援多選,並且所有選項均可選擇
toCheck(id){ if(this.orderarr.length==0){//判斷當前id陣列是否為空,若是為空,則直接push this.orderarr.push(id) }else{ if(this.orderarr.includes(id)){//判斷當前點選的選項是否已經被選擇了 this.orderarr.forEach((val,index) => { if(val==id){//若被選擇,則清除調當前選項 this.orderarr.splice(index,1); } }); } else{ this.orderarr.push(id)//若沒有被選擇,則直接push } } console.log(this.orderarr); },
3:支援多選,並且,當某選項只可單選時,其他選項禁止點選;
<view v-show="isSuperpose"> 當前為已選中狀態,其中其他選項不可點選 <image v-if="couponArr.length!=0" @click="toCheck(c)" class="check" :src="couponArr.includes(c.id)?'/static/img/check.png':'/static/img/checkDisable.png'"></image> <image v-else @click="toCheck(c)" class="check" src="/static/img/checkbox.png"></image> </view> <view v-show="!isSuperpose"> 當前為已選中狀態,其中其他選項可以點選選擇 <image v-if="couponArr.length!=0" @click="toCheck(c)" class="check" :src="couponArr.includes(c.id)?'/static/img/check.png':'/static/img/checkbox.png'"></image> <image v-else @click="toCheck(c)" class="check" src="/static/img/checkbox.png"></image> </view>
toCheck方法
toCheck(item){ console.log(item.superpose); if(this.isSuperpose){//如果當前除已選中狀態外,其他選項不可點選 if(this.couponArr.includes(item.id)){//判斷當前點選的是否已經被選擇,若當前選項已被選擇,則當前點選操作是取消選中,並可以選擇其他選項 this.couponArr.forEach((val,index) => { if(val==item.id){ this.couponArr.splice(index,1); } }); this.isSuperpose=false } else{
//因為其與選項不可點選,所以不作操作 } }else{ if(item.superpose==1){//我們是在介面中返回是當前選擇項是否可多選,當值為1時,不可多選 if(this.couponArr.length==0){ this.couponArr.push(item.id)//未選中時,直接push }else{ console.log(this.couponArr);//若有已選中選項,但由於當前項只可單選,則直接清空couponArr,在push this.couponArr=[] this.couponArr.push(item.id) } this.isSuperpose=true//並將狀態修改成其他選項不可選擇 }else{//若當前選擇項可以多選 if(this.couponArr.length==0){ this.couponArr.push(item.id)//未選中時,直接push }else{剩下多選的邏輯則同上 if(this.couponArr.includes(item.id)){ this.couponArr.forEach((val,index) => { if(val==item.id){; this.couponArr.splice(index,1); } }); } else{ this.couponArr.push(item.id) } } this.isSuperpose=false } } },