[vue]input type="radio"

자주 등장하는 input type="radio"를 제어해보자

  <div>
   	<input type="radio" v-model="radioValues" value="1"/>
    <input type="radio" v-model="radioValues" value="2"/>
    <input type="radio" v-model="radioValues" value="3"/>
    <input type="radio" v-model="radioValues" value="4"/>
    내가 선택한 radiotnstjsms {{radioValues}}!! <br>
    <button @click="radioValues=1" class="btn"> 클릭하면 1번체크</button>
    <button @click="radioValues=''" class="btn">클릭하면 체크해제
  </div>
  ...
  data(){
  	return{
    	radioValues:""
    }
  }

radio 버튼은 반드시 하나의 요소만 담기 때문에 v-model로 연결시킨 테이터는 value값을 가지게 된다

css

.btn {
  border: 1px solid red;
}
[type="radio"]:checked,
[type="radio"]:not(:checked) {
  display: none;
}
[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}
[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}
[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: "";
  width: 12px;
  height: 12px;
  background: #f87da9;
  position: absolute;
  top: 4px;
  left: 4px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}
[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}
[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}

라벨을 추가하고 v-for로 코드를 간결하게 정리해보자

<div>
          <p v-for="(item, index) in 4" :key="item.i">
            <input
              type="radio"
              v-model="radioValues"
              :value="index + 1"
              :id="'radio' + (index + 1)"
            />
            <label :for="'radio' + (index + 1)">{{ index + 1 }}번</label>
          </p>
          <br />
          내가 선택한 radio순서는 {{ radioValues }}!!<br /><br />
          <button @click="radioValues = 1" class="btn">클릭하면 1번체크</button>
          <button @click="radioValues = ''" class="btn">
            클릭하면 체크해제
          </button>
        </div>

결과

좋은 웹페이지 즐겨찾기