Vue 5
Vue 5
title: 5장 이벤트 처리
5장 이벤트 처리
5.1 이벤트 개요
- 예시:
1
<button @click="alert('클릭됨!')">클릭</button>
- 클릭 할 경우 alert 이벤트를 발생함.
5.2 인라인 이벤트 처리
- 예시:
1
<button @click="count = count + 1">카운트: 9</button>
- 버튼 클릭 시 변수 count 값 증가
5.3 이벤트 핸들러 메서드
- 예시:
1
2
3
4
5
6
7
8
9
10
<button @click="handleClick">클릭</button>
<script>
export default {
methods: {
handleClick() {
console.log('클릭!');
}
}
}
</script>
- 클릭이벤트 발생시에 console.log
5.4 이벤트 객체
- 예시:
1
2
3
4
5
6
7
8
9
10
<button @click="showEvent($event)">클릭</button>
<script>
export default {
methods: {
showEvent(e) {
console.log(e.target);
}
}
}
</script>
- 이벤트 객체를 설정하여 속성 값인 target을 액세스 할 수 있다.
- 이벤트 객체에는 e.type e.currentTarget e.clientx e.clinetY 등이 존재한다
5.5 기본 이벤트
- 예시:
1
2
3
4
5
6
7
8
9
10
<form @submit.prevent="submitForm">제출</form>
<script>
export default {
methods: {
submitForm() {
console.log('제출됨');
}
}
}
</script>
- 기본 동작을 막고 커스텀 로직을 실행합니다.
5.6 이벤트 전파와 버블링
- 예시:
1
2
3
<div @click="log('div')">
<button @click.stop="log('button')">클릭</button>
</div>
.stop으로 버블링을 멈출 수 있다.
5.7 이벤트 수식어
5.7.1 once 수식어
- 예시:
1
<button @click.once="alert('한 번만!')">클릭</button>
- 이벤트가 한 번만 실행
5.7.2 키코드 관련 수식어
- 예시:
1
<input @keyup.enter="submit" placeholder="엔터 입력" />
- 엔터 키 입력 시 이벤트 발생
5.7.3 마우스 관련 수식어
- 예시:
1
<button @click.right="alert('오른쪽 클릭!')">클릭</button>
- 우클릭시에 알러트 이벤트 발생
5.7.4 exact 수식어
- 예시:
1
<button @click.ctrl.exact="alert('Ctrl만!')">클릭</button>
- exact 시에는 Ctrl 키만 눌렀을 때 동작
This post is licensed under CC BY 4.0 by the author.