programming/Vue
[Vue] 하위 input 컴포넌트에 상위 data 연결 (emit & v-model)
euuuuuz:
2022. 7. 19. 23:27
[TODO]
- page/test.vue
test 페이지 안에서 form 데이터들(name, phone, email 등등) 을 변수로 관리하고,
그 데이터들을 모아서 백엔드로 전달
input 태그 가 특정 컴포넌트로 쌓여서 template에 바로 쓰이지 않고, 하위 컴포넌트 안에 들어가야함
[SOLUTION#1]
- emit으로 하위 컴포넌트 데이터(e.target.value) 를 상위 컴포넌트(page/test.vue) 로 전달
# 상위 컴포넌트 (pages/test.vue)
<template>
<SearchInput
:search-keyword="searchKeyword"
@input="updateSearchKeyword"
></SearchInput>
</template>
<script>
methods: {
updateSearchKeyword(keyword) {
this.searchKeyword = keyword
}
}
</script>
# 하위 컴포넌트 (components/SearchInput.vue)
<template>
<div>
<input
type="text"
:value="searchKeyword"
@input="$emit('input', $event.target.value)"
/>
<button type="button" @click="$emit('search')">search</button>
</div>
</template>
<script>
export default {
props: {
searchKeyword: {
type: String,
default: () => '',
},
},
}
</script>
[SOLUTION#2]
- v-model 사용
# 상위 컴포넌트 (pages/test.vue)
<template>
<SearchInput
v-model="searchKeyword"
:search-keyword="searchKeyword"
></SearchInput>
</template>
<script>
</script>
# 하위 컴포넌트 (components/SearchInput.vue)
<template>
<div>
<input
type="text"
:value="value"
@input="$emit('input', $event.target.value)"
/>
<button type="button" @click="$emit('search')">search</button>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: () => '',
},
},
}
</script>