重构微信小程序单选(Radio)、多选(checkbox)组件

时间:2025-04-02 18:24:07
  • Component({
  • behaviors: ['wx://form-field'],
  • properties: {
  • name:{
  • type:String,
  • },
  • mode:{
  • type:String,
  • value:'radio',
  • },
  • value:{
  • type:Array,
  • value:[],
  • },
  • theme:{
  • type:String,
  • value:'default',
  • },
  • range:{//disabled:true不可选中;chosed:true,已选中
  • type: Array,
  • value:[{code:'aaa',text:'第一排',disabled:false,chosed:true}]
  • },
  • },
  • data: {
  • num:null,
  • },
  • methods: {
  • tapChose:function(evt){
  • let _num = evt.currentTarget.dataset.num;
  • if (this.data.range[_num].disabled) {
  • return ;
  • }
  • if (this.data.mode=='radio') {
  • this.setData({
  • num:_num,
  • value:[this.data.range[_num].code],
  • });
  • }else if(this.data.mode=='checkbox'){
  • let _range = this.data.range;
  • let _value =[];
  • _range[_num].chosed=!_range[_num].chosed;
  • _range.forEach((v,i) => {
  • if (v.chosed) {
  • _value.push(v.code)
  • }
  • });
  • this.setData({
  • range:_range,
  • value:_value
  • });
  • }
  • let data=this.data.value;
  • this.triggerEvent('Change',data)
  • },
  • }
  • })