微信小程序复选框实现多选一功能过程解析

来自:互联网
时间:2020-05-27
阅读:

这篇文章主要介绍了微信小程序复选框实现多选一功能过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

功能实现界面

微信小程序复选框实现多选一功能过程解析

data: {
  checkboxItems: [
   { name: '全天(1-8节)', value: 'allday' },
   { name: '上午(1-4节)', value: 'am' },
   { name: '下午(5-8节)', value: 'pm' },
   { name: '晚上(晚自习)', value: 'night' },
  ]
 }

想要实现的功能

四个复选框中只能选一个,且选中另一个会取消其余选中,且能保存选择的value值

JS代码实现

checkboxChange: function (e) {
  var that = this;
  let checkboxValues=null;
  let checkboxItems = this.data.checkboxItems, values = e.detail.value
  for (var i = 0, lenI = checkboxItems.length; i < lenI; ++i) {
   if(checkboxItems[i].value==values[values.length-1]){
    checkboxItems[i].checked=true;
    checkboxValues = checkboxItems[i].value;
   }
   else{
    checkboxItems[i].checked = false;
   }
  }
  console.log(checkboxValues)
  that.setData({ checkboxItems, checkboxValues })
 }

前端代码

<view class="weui-cells weui-cells_after-title">
   <checkbox-group class="weui-flex" bindchange="checkboxChange">
    <label class="weui-cell weui-check__label weui-flex__item" wx:for="{{checkboxItems}}" wx:key="value">
     <checkbox class="weui-check" value="{{item.value}}" checked="{{item.checked}}" />
     <view class="weui-cell__hd weui-check__hd_in-checkbox">
      <icon class="weui-icon-checkbox_circle" type="circle" size="23" wx:if="{{!item.checked}}"></icon>
      <icon class="weui-icon-checkbox_success" type="success" size="23" wx:if="{{item.checked}}"></icon>
     </view>
     <view class="weui-cell__bd">{{item.name}}</view>
    </label>
   </checkbox-group>
  </view>

对应的CSS样式是

WeUI

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

返回顶部
顶部