微信小程序 - 下拉列表的实现
微信小程序目前提供两种方式实现下拉列表:action-sheet 与 picker选择器
action-sheet
action-sheet 有两种方法实现下拉,第一种使用action-sheet 标签,第二种是使用wx.showActionSheet方法
(1)action-sheet 标签
<action-sheet bindchange="actionSheetChange" hidden="{{actionType}}">
<block wx:for="{{actionSheetItems}}" wx:key="*this">
<action-sheet-item class="item" bindtap="bindItemTap" data-name="{{item}}">
{{item}}
</action-sheet-item>
</block>
<action-sheet-cancel class="cancel">取消</action-sheet-cancel>
</action-sheet>
<view>
<input type="text" name="type" value="{{addTypeData}}" disabled="{{addTypeDis}}"
bindfocus="addType" placeholder="请输入所在城市" style="border:1px solid black;margin:15px;"/>
</view>
Page({ data:{ actionSheetItems : ['北京','上海','郑州','南京','成都','青岛','石家庄'], addTypeDis : false, actionType : true, addTypeData : "" }, addType : function(event){ this.setData({ addTypeDis : true, actionType :false, typeClass : " " }) }, bindItemTap:function(e){ this.setData({ addTypeDis : false, actionType :true, addTypeData :e.currentTarget.dataset.name, }) }, actionSheetChange: function(e) { this.setData({ addTypeDis : false, actionType : true, }) } })
注意:actionSheetItems数组最大长度为6,超过6个就不会显示。
效果如图:
(2)wx.showActionSheet(Object)
<input disabled="{{addLevelDis}}" type="text" bindfocus="addLevel" value="{{addLevelData}}"
style="border:1px solid black;margin:20px;" placeholder="请输入用户级别"/>
Page({ data:{ actionSheetLevelItems : ['A','B','C','S'], addLevelData: "", addLevelDis: false }, addLevel : function(event) { this.setData({ addLevelDis: true }) var that = this wx.showActionSheet({ itemList: that.data.actionSheetLevelItems, success: function(res) { if (!res.cancel) { that.setData({ addLevelData:that.data.actionSheetLevelItems[res.tapIndex] }) } that.setData({ addLevelDis: false }) } }) } })
效果如图:
picker 选择器
滚动选择器,现支持三种选择器,通过mode来区分,分别是普通选择器,时间选择器,日期选择器,默认是普通选择器。 (1)普通选择器:mode = selector (2)时间选择器:mode = time (3)日期选择器:mode = date |
<view style="border:1px solid black; margin: 15px;">
<view class="section" style="margin:20px;">
<picker mode="selector" bindchange="bindPickerChange" value="{{arrayIndex}}" range="{{array}}" name="area">
<view class="picker">
地区:{{array[arrayIndex]}}
</view>
</picker>
</view>
<view class="section" style="margin:20px;">
<picker mode="time" value="{{time}}" start="00:00" end="23:59" bindchange="bindTimeChange" name="time">
<view class="picker">
时间:{{time}}
</view>
</picker>
</view>
<view class="section" style="margin:20px;">
<picker mode="date" value="{{date}}" start="2015-09-01" end="2017-09-01" bindchange="bindDateChange" name="date">
<view class="picker">
日期:{{date}}
</view>
</picker>
</view>
</view>
Page({ data:{ array: ['中国', '美国', '巴西', '日本'], arrayIndex: 0, date: '2016-09-01', time: '09:00' }, bindPickerChange: function(e) { this.setData({ arrayIndex: e.detail.value }) }, bindDateChange: function(e) { this.setData({ date: e.detail.value }) }, bindTimeChange: function(e) { this.setData({ time: e.detail.value }) } })
效果如图: