📌 input 데이터 값 받아오기
Modal.vue 에서 input 을 넣어보자
<template>
<div class="black-bg" v-if="isModal === true">
<div class="white-bg">
<img :src="prodList[prodId].image" alt="prod-image" style="width:100%">
<h4>{{prodList[prodId].title}}</h4>
<p>{{prodList[prodId].content}}</p>
<input>
<p>{{prodList[prodId].price}} 원</p>
<button @click="$emit('closeModal')">닫기</button>
</div>
</div>
</template>
가격 위에 input 창이 생겼다.
저 input 창에 숫자(개월)을 입력하면 개월 수만큼 곱해진 가격이 노출되게 만들어보자.
먼저 개월을 담을 데이터를 생성해야 한다.
데이터 보관함에 month 를 초기화 한다.
초기값 설정을 아무렇게나 하면 안 되고 알맞은 데이터로 해야 한다.
(ex. textarea 라면 문자로 초기화를 해야 한다. 숫자로 초기화하면 안됨)
data() {
return {
month: 0
}
}
$event.target.value 를 통해 input 값을 받아 올 수 있다.
아래처럼 코드를 작성하면 month 라는 변수에 input 의 value 를 받아온다.
<input @input="month = $event.target.value">
실제로 출력해보면,
<template>
<div class="black-bg" v-if="isModal === true">
<div class="white-bg">
<img :src="prodList[prodId].image" alt="prod-image" style="width:100%">
<h4>{{prodList[prodId].title}}</h4>
<p>{{prodList[prodId].content}}</p>
<input @input="month = $event.target.value">
{{ month }}
<p>{{prodList[prodId].price}} 원</p>
<button @click="$emit('closeModal')">닫기</button>
</div>
</div>
</template>
잘 출력되고 있는 것을 확인할 수 있다.
선택한 개월 수 * price 를 곱하면 원하는 값이 출력된다.
<p>{{month}}개월 선택함 : {{prodList[prodId].price * month}}원</p>
📌 v-model 활용
v-model = "데이터이름"
을 활용하면 input value 를 데이터이름으로 바로 활용할 수 있다'
v-model = "month"
input value 가 곧 month 라는 변수에 저장된다.
@input = "실행할 코드"
$event.target.value : 사용자의 input value
v-model="데이터이름"
- input의 value 데이터를 초기화할 때 알맞는 자료형으로 하기
- 사용자가 <input>에 입력한 것은 모두 문자 자료형
모든 input 속성은 v-model 을 사용할 수 있다. (ex. textarea)
<input v-model="month">
<p>{{month}}개월 선택함 : {{prodList[prodId].price * month}}원</p>
⚡ 주의) 사용자가 <input>에 입력한 것은 전부 문자자료형이다.
input 으로 입력받은 값을 모두 숫자형으로 받고 싶다면 directive 을 사용하자
v-model.number="데이터이름"
<input v-model.number="month">
입력받은 값을 숫자형으로 바꿔주는 것이지 문자형 입력을 막아주는 것은 아니다.
📌 watcher
watcher : data 를 감시하는 함수
input 에 문자를 입력하면 경고를 띄우고 싶다면? watcher 를 활용하면 된다.
⚡ 함수명을 내가 감시하고 싶은 데이터명으로 작명해야 한다
watch : {
month(){
//month가 변경될 때 실행할 코드
}
}
month 가 변경될 때마다 month() 함수가 실행된다.
month(a) 안의 파라미터는 아무거나 작명 가능하다.
a 는 month 가 변경될 값을 의미한다.
month(a,b)
a: 변경 될 값
b: 변경 전 값
input value 가 12가 초과되면 alert 를 띄워보자
watch: {
month() {
if (this.month > 12 ){
alert('12개월을 초과할 수 없습니다');
}
}
}
1 누르고 3을 누르는 순간 alert 가 노출된다.
이메일 형식을 입력했는지,
숫자나 문자만 입력했는지,
입력한 값에 영어 대문자가 들어있는 지 등 검사하기 위해서는
정규식을 이용하거나 Vue 용 form validation 라이브러리를 쓰기도 한다.
'Vue3 > 코딩애플 part1' 카테고리의 다른 글
[Vue/코딩애플/part1] 12. 상품 정렬 기능 / 데이터 원본 보존 (0) | 2024.07.30 |
---|---|
[Vue/코딩애플/part1] 11. UI 애니메이션 효과 주기 / transition (0) | 2024.07.30 |
[Vue/코딩애플/part1] 9. custom event (자식이 부모 데이터 바꿀 때) (0) | 2024.07.29 |
[Vue/코딩애플/part1] 8. props (0) | 2024.07.29 |
[Vue/코딩애플/part1] 7. 컴포넌트(Component) / 컴포넌트 파일명 한 단어로 가능하게 하는 방법 (0) | 2024.07.29 |