這是我第6篇簡(jiǎn)書。
要實(shí)現(xiàn)下圖的效果(自定義多選單選),大多數(shù)公司項(xiàng)目的多選框都是自己設(shè)計(jì)的,所以用原生標(biāo)簽或者組件是不可行的,最簡(jiǎn)單的是自己綁定事件,然后切換選擇和未選擇的圖片。而小程序和vue一樣是沒法操作dom的,所以要利用數(shù)組的下標(biāo)和自定義屬性來進(jìn)行三元判斷。

直接上代碼:
一. 自定義多選
wxml:
<view class="sel-box">
/**用wx:for來進(jìn)行列表渲染**/
<view wx:for="{{repContent}}" class="multi-selection">
<text>{{item.message}}</text>
/**利用數(shù)組的下標(biāo)index來進(jìn)行判斷是哪個(gè)的事件**/
<image src="{{selectIndex[index].sureid? hasSelect : noSelect}}" class="multi-img" data-selectIndex="{{index}}" bindtap="selectRep" />
</view>
</view>
js:
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
noSelect: 'https://xxxxx/ic_report_nor@2x.png',
hasSelect: 'https://xxxxx/ic_check_ele@2x.png',
repContent: [{ message: '廣告內(nèi)容' }, { message: '不友善內(nèi)容' }, { message: '垃圾內(nèi)容' }, { message: '違法違規(guī)內(nèi)容' }, { message: '其他' }],
selectIndex: [
{ sureid: false },
{ sureid: false },
{ sureid: false },
{ sureid: false },
{ sureid: false },
],
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad: function (options) {
},
selectRep:function(e){
let index = e.currentTarget.dataset.selectindex; //當(dāng)前點(diǎn)擊元素的自定義數(shù)據(jù),這個(gè)很關(guān)鍵
let selectIndex = this.data.selectIndex; //取到data里的selectIndex
selectIndex[index].sureid = !selectIndex[index].sureid; //點(diǎn)擊就賦相反的值
this.setData({
selectIndex: selectIndex //將已改變屬性的json數(shù)組更新
})
}
})
二. 自定義單選
實(shí)際上是組件id、自定義id配合數(shù)組下標(biāo)index的應(yīng)用:
wsml:
<view class="sel-box">
<view wx:for="{{repContent}}" class="multi-selection">
<text>{{item.message}}</text>
<image src="{{index == id? hasSelect : noSelect}}" data-id="{{index}}" class="multi-img" bindtap="selectRep" />
</view>
</view>
js:
selectRep:function(e){
var ids = e.currentTarget.dataset.id; //獲取自定義的id
this.setData({
id: ids //把獲取的自定義id賦給當(dāng)前組件的id(即獲取當(dāng)前組件)
})
},
currentTarget:事件綁定的當(dāng)前組件。
dataset:在組件中可以定義數(shù)據(jù),這些數(shù)據(jù)將會(huì)通過事件傳遞給 SERVICE。 書寫方式: 以data-開頭,多個(gè)單詞由連字符-鏈接,不能有大寫(大寫會(huì)自動(dòng)轉(zhuǎn)成小寫)如data-element-type,最終在 event.currentTarget.dataset 中會(huì)將連字符轉(zhuǎn)成駝峰e(cuò)lementType。
id:當(dāng)前組件的id