반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- e2e
- CSS
- JavaScript
- https
- Cypress
- vue-cli
- devtools
- msw
- ViTE
- vue3
- SSR
- 비동기
- rendering
- caching
- api test
- TLS
- Testing
- custom command
- vue
- svelte
- csr
- http3
- QUIC
- CloudFlare
- web vital
- import.meta.env
- 선택자
- ts error
- aws
- typeScript
Archives
- Today
- Total
Develop Note by J.S.
[Vue3] v-model 본문
반응형
v-model은 컴포넌트 또는 Form 입력에서 데이터의 양방향 바인딩을 구현하기 위해 사용하는 디렉티브입니다.
Form입력
1. input text
// v-bind, event listener 사용 시
<input
:value="text" // v-bind:value="text"
@input="event => text = event.target.value" // v-on:input="event ..."
/>
<p>메세지: {{ text }}</p>
// v-model 사용으로 코드의 단순화
<input v-model="text" />
<p>메세지: {{ text }}</p>
2. checkbox
// checkbox 단일 체크
<input type="checkbox" id="checkbox" v-model="checked" />
<label for="checkbox">{{ checked }}</label> // boolean 값을 사용
// checkbox 다중 체크
<div>체크된 이름: {{ checkedNames }}</div> // Array 값을 사용
<input type="checkbox" id="jack" value="잭" v-model="checkedNames">
<label for="jack">젝</label>
<input type="checkbox" id="john" value="존" v-model="checkedNames">
<label for="john">존</label>
3. radio button
// radio Button
<div>선택한 것: {{ picked }}</div>
<input type="radio" id="one" value="하나" v-model="picked" />
<label for="one">하나</label>
<input type="radio" id="two" value="둘" v-model="picked" />
<label for="two">둘</label>
4. select
// 단일 셀렉트
<div>선택됨: {{ selected }}</div> // 단일 value 값을 사용
<select v-model="selected">
<option>가</option>
<option>나</option>
</select>
// 다중 셀렉트
<div>선택됨: {{ selected }}</div> // Array 값을 사용
<select v-model="selected" multiple> //다중선택 옵션
<option>가</option>
<option>나</option>
<option>다</option>
</select>
컴포넌트 v-model
form입력 시 사용하는 v-model 디렉티브의 동작을 컴포넌트에서도 구현할 수 있습니다.
// form과의 차이점은 하위컴포넌트에서의 props의 name과 emit되는 event name이 고정됩니다.
//컴포넌트의 v-model 사용
<CustomInput v-model="searchText" />
//CustomInput 컴포넌트
<script setup>
defineProps(['modelValue']) // 고정name
defineEmits(['update:modelValue']) // 고정name
</script>
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
기본적으로 컴포넌트에서 v-model사용 시 'modelValue'를 프로퍼티로, 'update:modelValue'를 이벤트로 사용합니다. 만일 인자를 전달하여 이름을 수정할 수도 있습니다.
//v-model:title로 연결
<MyComponent v-model:title="title" />
//MyComponent
<script setup>
defineProps(['title'])
defineEmits(['update:title'])
</script>
<template>
<input
type="text"
:value="title"
@input="$emit('update:title', $event.target.value)"
/>
</template>
참고사이트
https://v3-docs.vuejs-korea.org/guide/components/v-model.html
반응형
'FrontEnd > Vue3' 카테고리의 다른 글
[Vue3] 다중 Instance (0) | 2023.06.30 |
---|---|
[Vue3] Provide/ Inject (0) | 2023.06.28 |
[Vue3] Watch (0) | 2023.06.19 |
[Vue3] Computed (0) | 2023.06.19 |
[Vue3] Composition API(2) (0) | 2023.06.19 |