微信小程序:多选及单选组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012615439/article/details/90669423

1.组件wxml:

<view 
    class="radio {{mode=='radio' ? 'circle':''}}"
    wx:for="{{sourceData}}"
    wx:key="index"
    bindtap='_clickHandle'
    data-index="{{index}}"
    data-value="{{item}}"
    data-key="{{key}}"
>
  <view 
    class="radio-icon {{item.checked ? 'active':''}}"
    style="width:{{size}}rpx;height:{{size}}rpx;"
  >
    <view class="icon"></view>
  </view>
  <view class="radio-text" data-label="{{item[label]}}">{{item[aaa]}}</view>
</view>

2.组件wxss:

.radio{
  display:flex;
  flex-direction:row;
  align-items:center;
  margin-bottom:20rpx;
}
.radio.circle .radio-icon{
  border-radius:50%;
}
.radio .radio-icon.active{
  background-color:#409eff;
  border-color:#409eff;
}
.radio .radio-icon.active .icon{
  transform:rotate(45deg) scaleY(1);
}
.radio-icon{
  width:40rpx;
  height:40rpx;
  margin:0 20rpx;
  overflow:hidden;
  border-radius:4rpx;
  border:1px solid #ccc;
  transition: transform .15s ease-in .05s;
}
.icon{
  width:30%;
  height:70%;
  border:2px solid #fff;
  border-top:0;
  border-left: 0;
  margin:4rpx auto;
  transform:rotate(45deg) scaleY(0);
  transition: transform .15s ease-in .05s;
}

3.组件js:

// groups/groups.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    source:{
      type:Array
    },
    key:{
      type:String
    },
    mode:{
      type:String
    },
    size:{
      type:Number,
      value:60
    },
    aaa:{
      type:String,
      value:"label"
    }
  },
  created(){
    this.setData({
      sourceData:this.data.source
    })
  },
  /**
   * 组件的初始数据
   */
  data: {
    sourceData:[],
    selectData:[]
  },
  observers:{
    "source":function(newVal){
      this.setData({
        sourceData:newVal
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    _clickHandle:function(e){
      var _this = this;
      var idx = e.currentTarget.dataset.index;
      var temp = this.data.sourceData;
      if(this.data.mode == "radio"){
        temp.forEach(function(item,index){
          index == idx ? (temp[idx].checked = !temp[index].checked) : (temp[index].checked = false);
        })
      }else{
        temp[idx].checked = !temp[idx].checked;
      }
      this.setData({
        sourceData:temp
      });
      console.log("sourceData", this.data.sourceData)
      this.data.selectData.length = 0;//数组清零
      this.data.sourceData.forEach(function(item){
        if(item.checked){
          _this.data.selectData.push(item[_this.data.key])
        }
      });
      var myEventDetail = Array.from(new Set(this.data.selectData));
      this.triggerEvent('myevent', { selectData: myEventDetail.join(',')});
    }
  }
})

4.组件json:

{
  "component": true,
  "usingComponents": {}
}

5.组件调用:

<group source="{{data}}" bindmyevent="myevent" key="val" mode="radio" size="40" label="label"></group>

猜你喜欢

转载自blog.csdn.net/u012615439/article/details/90669423