# Form Input Bindings
form을 처리할 때 사용자가 input에 입력하는 값을
실시간으로 JavaScript 상태에 동기화해야하는 경우
= 양방향 바인딩
하는 방법? 1) v-bind와 v-on 함께 사용 2) v-model 사용
1) v-bind와 v-on 함께 사용
- v-bind: input 요소의 value 속성 값을 입력 값으로 사용
- v-on: input 이벤트가 발생할 때마다 input 요소의 value 값을 별도 반응형 변수에 저장하는 핸들러 호출
const inputText1 = ref('')
const onInput = function (event) {
inputText1.value = event.currentTarget.value
}
<p>{{inputText1}}</p>
<input type="text" @input="onInput" :value="inputText1">

→ 근데 너무 번거롭다
2) v-model 사용
const inputText2 = ref('')
<p>{{ inputText2 }}</p>
<input type="text" v-model="inputText2">

근데...영어 빼고는 바로바로는 아니고 조금 느림
그래서 한글로 빨리 쓸거면 위의 방법 사용
# v-model의 활용 예시
(1) boolean 값
const checked = ref(false)
<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{checked}}</label>


사용자가 체크 박스를 체크하면 바뀐다
(2) 어떤 항목을 체크했는지 확인해보기
const checkedNames = ref([])
<div>Checked names: {{ checkedNames }}</div>
<input type="checkbox" id="alice" value="Alice" v-model="checkedNames">
<label for="alice">Alice</label>
<input type="checkbox" id="bella" value="Bella" v-model="checkedNames">
<label for="bella">Bella</label>

(3) select 활용하기
const selected = ref([])
<div>Selected: {{ selected }}</div>
<select v-model="selected">
<option disabled value="">Please select one</option>
<option>Alice</option>
<option>Bella</option>
<option>Cathy</option>
</select>

선택한 사람이 뜨게 할 수 있다
추가적인 건 공식문서 참고
'FrontEnd > Vue' 카테고리의 다른 글
| [Vue] Computed 속성 (1) | 2023.11.06 |
|---|---|
| [Vue] TodoList 만들어보기 (0) | 2023.11.02 |
| [Vue] v-on (0) | 2023.11.02 |
| [Vue] v-bind (Attribute, Class, Style) (0) | 2023.11.02 |
| [Vue] Directive (0) | 2023.11.02 |