Realize radio single button click unchecked state

Requirements : Some radio content in the project can be set to be selected by default or not, but generally after using radio, after selecting one of them, all radios cannot be restored to the initial unselected state, as shown in the following figure:

You can only select one of the following radio boxes, and you can also unselect all of them. At the same time, if you select one of them, you can also cancel it, and finally you can return to the state of unselecting all.

Next, let's introduce how to realize the method of unchecking the radio button:

// HTML代码
<div v-for="day in weekSelectList" :key="day.id" class="select__day">
  <input
    type="radio"
    name="week"
    :id="day.label"
    :value="day.value"
    v-model="selectedDay"
    @click="onClick(day.value)"
  />
  <label :for="day.label">{
    
    { day.label }}({
    
    { day.value }})</label>
</div>
// vue3 + ts中的js代码
setup() {
  // 单选数据
  const weekSelectList = [
    { label: "周一", value: "2018-12", id: 1 },
    { label: "周二", value: "2018-13", id: 2 },
    { label: "周三", value: "2018-14", id: 3 },
    { label: "周四", value: "2018-15", id: 4 },
    { label: "周五", value: "2018-16", id: 5 },
  ];
  // selectedDay 双向绑定值 如果想要默认选中,修改初始值就行 ,这里我默认不选中,所以为""
  const selectedDay = ref("");
  const onClick = (val: any) => {
    // 判断当前的数据是否与绑定的值相同
    if (val == selectedDay.value) {
      selectedDay.value = "";  // 相同则取消选中将 selectedDay的值重置为""
    } else {
      selectedDay.value = val; // 不同就将当前的值赋予selectedDay
    }
  };
  return {
    weekSelectList,
    selectedDay,
    onClick,
  };
},

The final result, as shown below:

Guess you like

Origin blog.csdn.net/JJ_Smilewang/article/details/127908646