天天看点

vue绑定单选框(radio)和复选框(CheckBox)

vue绑定单选框(radio)和复选框(CheckBox)
html部分
<div style="width:500px;margin:50px auto;display:flex;flex-direction:column;">
        <div style="font-weight:600;font-size:18px">问卷调查</div>
        
        <div v-for="(item,index) in question" :key="index" style="padding-top:10px">
          <div style="margin-bottom:10px">{{item.title}}</div>
          <div v-if="item.sex" style="display:flex;align-items:center;">
          
            <div v-for="(item2,index2) in item.sex" :key="index2" @click="chooseSex(item2)" style="margin-right:20px">
              <input type="radio" :value="item2" v-model="radio2">  <span>  {{item2}}</span>
            </div>
          </div>

          <div v-if="item.item" style="display:flex;align-items:center;">
            <div v-for="(item3,index3) in item.item" :key="index3"  @click="chooseHobbied(item3)"  style="margin-right:20px">
              <input type="checkbox" :value="item3" v-model="checkbox"><span>  {{item3}}</span>
            </div>
          </div>
        </div>
      </div>
           
vue数据绑定
data() {
  return {
    radio2:'',
    checkbox:[],
    question:[
      {
        title:"1、请选择你的性别",
        sex:[
          '男','女'
        ]
      },
      {
        title:"2、请选择你的爱好",
        item:[
          '打球','读书','画画','游泳','跑步'
        ]
      }
    ], 
  };
},
           
js部分
//单选框radio选中值的改变
chooseSex(item){
        this.radio2 = item;
        console.log("点击",item,"值",this.radio2);
      },
      
       //复选框checkbox多项选择后的值,及取消选中后的其他值
      chooseHobbied(item){
        if(box.indexOf(item) === -1){
          box.push(item);
          this.checkbox = box;
          console.log("点击",item,"值",box);
        }else{
            box.splice(box.indexOf(item),1);
          console.log("box值",box);
          this.checkbox = box;
        }
      },