본문 바로가기

Vue.js

[Udemy Vue 완벽가이드 Section11] 145. 체크박스 및 라디오 버튼과 함께 v-model 사용하기

체크박스와 라디오버튼도 form에 있다.

 

## 체크박스 vs 라디오버튼 차이

체크박스와 라디오버튼의 차이는,

- 체크박스 : 한번에 여러 개 선택 가능.

- 라디오버튼 : (name속성이 동일하다면) 한번에 한개만 선택 가능.

 

**참고

[ 체크박스 ]

HTML에서 체크박스는 type속성이 'checkbox'인 input태그로 만든다.

- name : 체크박스의 이름. 같은 분류의 체크박스는 같은 이름으로 지정해준다.

- value : 선택항목들이 가지는 고유한 값. submit하면 서버로 전송될 값

- id : label의 for속성값과 같으면 그 label과 연결된다.

 

[ 라디오버튼 ]

HTML에서 라디오버튼은 type속성이 'radio'인 input태그로 만든다.

- name : 라디오버튼의 이름. 같은 분류의 라디오버튼는 같은 이름으로 지정해준다.

- value : 선택항목들이 가지는 고유한 값. submit하면 서버로 전송될 값

- id : label의 for속성값과 같으면 그 label과 연결된다.

 

 

 

# 체크박스 및 라디오 버튼에서 값 가져오는 방법

위: 체크박스, 아래: 라디오버튼

<!--체크박스-->
<div class="form-control">
  <h2>What are you interested in?</h2>
  <div>
    <input
      id="interest-news"
      name="interest"
      type="checkbox"
      v-model="interest"
    />
    <label for="interest-news">News</label>
  </div>
  <div>
    <input
      id="interest-tutorials"
      name="interest"
      type="checkbox"
      v-model="interest"
    />
    <label for="interest-tutorials">Tutorials</label>
  </div>
  <div>
   <input
      id="interest-nothing"
      name="interest"
      type="checkbox"
      v-model="interest"
    />
    <label for="interest-nothing">Nothing</label>
  </div>
</div>

<!--라디오버튼-->
<div class="form-control">
  <h2>How do you learn?</h2>
  <div>
    <input
      id="how-video"
      name="how"
      type="radio"
      value="video"
      v-model="how"
    />
    <label for="how-video">Video Courses</label>
  </div>
  <div>
    <input
      id="how-blogs"
      name="how"
      type="radio"
      value="blogs"
      v-model="how"
    />
    <label for="how-blogs">Blogs</label>
  </div>
  <div>
    <input
      id="how-other"
      name="how"
      type="radio"
      value="other"
      v-model="how"
    />
    <label for="how-other">Other</label>
  </div>
</div>
data() {
 return {
    interest: null, //체크박스 값
    how: null, //라디오버튼 값
  };
},

체크박스, 라디오버튼의 각 input요소에 전부 v-model을 추가하자.

(참고로, v-model이 항상 맨 끝에 가야하는건 아니다. 속성목록 어디에 넣어도 괜찮다.)

그리고 체크박스는 v-model에 data 프로퍼티인 'interest'를, 라디오버튼은 'how'를 바인딩하자.

interest, how 모두 초기값을 null로 지정하자.

 

 

## 여러개의 체크박스의 경우 주의할점

 

1/ 초기값을 빈 배열로! [ ]

체크박스에서 "News"를 클릭하려고 하니, 체크박스 세개가 동시에 선택된다.

무엇이 잘못된걸까?

 

여러 체크박스에 같은 name을 붙이면 자동으로 그룹이 생성된다.

그룹 자체는 괜찮지만 체크박스를 개별로 처리할 수 있어야한다.

따라서 interest의 초기값을 null이 아닌, 빈 배열로 설정하자.

그러면 Vue는 유저가 선택한 요소들을 이 배열에 추가해준다.

data(){
 return {
    interest: [],
    how: null,
  };
},
methods: {
    submitForm() {
      console.log('Checkboxes');
      console.log(this.interest);
      console.log('Radio buttons');
      console.log(this.how);
      this.interest = []; //리셋
      this.how = null; //리셋
    },
  },

 

2/ 각 input요소에 서로다른 value 필수!

다시 리로딩하여 체크박스를 클릭해보면 하나씩 체크할 수 있다.

하지만 여전히 이상한 부분이 하나 있다.

체크박스 하나만 선택해제했는데 세개 전부가 같이 해제된다.

→ 체크박스 input요소에 value를 추가해야한다. 그리고 그 value는 input요소마다 다른 값으로 설정해야한다.

그렇지 않으면 Vue는 배열에 어떤 값을 추가해야할지 알 수 없다.

<div class="form-control">
  <h2>What are you interested in?</h2>
  <div>
    <input
      id="interest-news"
      name="interest"
      type="checkbox"
      value="news" <!--value추가-->
      v-model="interest"
    />
    <label for="interest-news">News</label>
  </div>
  <div>
    <input
      id="interest-tutorials"
      name="interest"
      type="checkbox"
      value="tutorials" <!--value추가-->
      v-model="interest"
    />
    <label for="interest-tutorials">Tutorials</label>
  </div>
  <div>
   <input
      id="interest-nothing"
      name="interest"
      type="checkbox"
      value="nothing" <!--value추가-->
      v-model="interest"
    />
    <label for="interest-nothing">Nothing</label>
  </div>
</div>

value속성은 HTML 기본 속성으로 내부적으로 사용되는 고유 식별자를 각 체크박스, 라디오버튼에 부여한다.

이제 새로고침을 해보면, 체크박스를 하나씩 선택할 수 있고, 선택 해제도 개별적으로 할 수 있다.

 

체크박스에서 'News', 'Nothing'을 선택하고, 라디오 버튼에는 'Video Courses'를 선택한 후 Save Data 버튼을 눌러보자.

콘솔로그를 보면,

체크박스는 [[ Target ]]항목에 선택했던 값이 배열로 있다.

라디오 버튼은 'Video Courses'의 value값인 'video'가 출력된다.

이렇게 체크박스와 라디오버튼에서 v-model과 value 속성을 이용하여 값을 추출할 수 있다.

 

## 체크박스가 하나만 있는 경우

체크박스가 하나만 있는 경우, input값은 어떻게 구할까?

이번에는 체크박스가 여러개 있는것이 아니라, confirm-terms라는 체크박스 하나만 있다.

(value속성은 없어도 된다.)

<div class="form-control">
  <input
    type="checkbox"
    id="confirm-terms"
    name="confirm-terms"
    v-model="confirm"
  />
  <label for="confirm-terms">Agree to terms of use?</label>
</div>

여기서도 v-model을 사용할 수 있다.

data프로퍼티에 confirm프로퍼티를 추가하고, 초기에는 false로 설정하자.

그리고 이 confirm프로퍼티를 v-model을 사용하여 input 요소에 바인딩하자.

data() {
  return {
    confirm: false,
  };
},
methods: {
  submitForm() {
    console.log('Confirm?');
    console.log(this.confirm);
    this.confirm = false;
  },
}

체크박스를 체크하고, 양식을 제출하면("Save Data"버튼을 클릭하면) 콘솔에 true가 출력된다.

 

 

만약 같은 name 속성을 가진 체크박스가 여러개 있다면 체크된 값을 요소로 갖는 '배열'이 생긴다.

특정 이름에 해당하는 체크박스가 하나라면, true / false 가 반환된다.

 

 

** 출처: 모든 내용은 Udemy Vue-완벽가이드 강의를 기반으로 작성하였습니다.