| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
- hoisting
- synchronus
- watch
- drective
- tdz
- reactivity
- ref
- const
- async
- computed
- Component
- await
- vue
- setup 함수
- asynchronus
- composition api
- composition API
- html 엔티티
- 오블완
- vitre
- 티스토리챌린지
- watchEffect
- 템플릿 문법
- es6
- eruda
- promise
- 앱 빌드
- mobile dev tools
- dex모드
- let
- Today
- Total
uxtry
vue: 이벤트 처리 본문

vue에서는 이벤트 처리를 위해 v-on 디렉티브를 사용합니다. 이 디렉티브는 HTML 요소에 이벤트 리스너를 연결하며, 축약형으로 @기호를 사용할 수 있습니다. Vue3에서는 Compositon API와 함께 이벤트를 더 동적으로 관리할 수 있는 기능도 제공됩니다.
1. 기본 이벤트 처리
기본적인 이벤트 처리는 v-on을 사용하여 특정 이벤트를 컴포넌트 메서드에 연결합니다.
예제: 클릭 이벤트
<template>
<button v-on:click="handleClick">클릭하세요</button>
<!-- 축약형 -->
<button @click="handleClick">축약형 클릭</button>
</template>
<script>
export default {
methods: {
handleClick() {
alert('버튼이 클릭되었습니다!');
},
},
};
</script>
★ Vue SFC Playground 코드 실행 →
위 코드에서 v-on:click 또는 @click은 버튼 클릭 이벤트를 handleClick메서드에 연결합니다.
2. 이벤트 전달
vue에서는 기본적으로 이벤트 객체($event)가 이벤트 핸들러에 전달됩니다.
예제: 이벤트 객체 사용
<template>
<input @input="handleInput" palceholder="입력하세요" />
</template>
<script>
export default{
methods: {
handelInput(event){
alert(event.target.value); //입력된 값 출력
},
},
};
</script></script>
★ Vue SFC Playground 코드 실행 →
여기서 event.target.value는 사용자가 입력한 값을 가져옵니다.
3. 인라인 메서드 호출
Vue에서는 이벤트 핸들러를 인라인으로 정의하거나 데이터를 메서드에 전달할 수 있습니다.
예제: 인수전달
<template>
<button @click="sayHello('vue')">클릭</button>
</template>
<script>
export default {
methods: {
sayHello(name){
alert(`안녕하세요, ${name}!`);
},
},
};
</script>
★ Vue SFC Playground 코드 실행 →
클릭하면 sayHello메서드가 호출되고, name 매개변수로 'vue'가 전달됩니다.
4. 이벤트 수식어
vue는 다양한 이벤트 수식어를 제공하여 이벤트 동작을 간단히 제어할 수 있습니다.
4.1. .stop: 이벤트 전파 중단
<template>
<div @click="parentClick">
<button @click.stop="childClick">클릭</button>
</div>
</template>
<script>
export default {
methods:{
parentClick(){
alert('부모가 클릭됨');
},
childClick(){
alrert('자식이 클릭됨');
}
},
};
</script>
★ Vue SFC Playground 코드 실행 →
버튼을 클릭해도 부모 div의 클릭 이벤트가 호출되지 않습니다.
4.2. .prevent: 기본 동작 방지
<template>
<form @submit.prevent="submitForm">
<button type="submit">제출</button>
</form>
</template>
<script>
export default {
methods: {
submitForm(){
alert('폼 제출이 막혔습니다!');
}
},
};
</script>
★ Vue SFC Playground 코드 실행 →
기본적으로 form태그는 제출 시 페이지를 새로고침하지만, .prevent를 사용하면 이를 방지합니다.
4.3. .self: 현재 요소에서만 이벤트를 실행
<template>
<div class="box" @click.self="handleBoxClick">
<span>내부 클릭 시 이벤트 발생</span>
</div>
</template>
<script>
export default {
methods: {
handleBoxClick() {
alert('박스 클릭!');
},
},
};
</script>
<style>
.box{background-color: green; padding:10px;}
.box span{display:inline-block; background-color: #fff;}
</style>
★ Vue SFC Playground 코드 실행 →
박스안의 텍스트를 클릭해도 이벤트가 실행되지 않고, 박스의 빈 공간을 클릭해야 실행됩니다.
4.4. .once: 이벤트를 한 번만 실행
<template>
<button @click.once="hadleClick">한 번만 클릭</button>
</template>
<script>
export default{
methods: {
handleClick(){
alert('이 버튼은 한 번만 클릭 가능합니다.');
}
},
};
</script>
★ Vue SFC Playground 코드 실행 →
버튼 클릭 이벤트는 한 번만 실행됩니다.
5. 키보드 이벤트
vue는 키보드 이벤트를 다루기 위해 키 수식어를 제공합니다.
예제: 특정 키 이벤트 처리
<template>
<input @keyup.enter="submitForm" placeholder="엔터를 눌러 제출"/>
</template>
<script>
export default {
methods: {
submitForm(){
alert('폼이 제출되었습니다!');
},
}
};
</script>
★ Vue SFC Playground 코드 실행 →
@keyup.enter는 Enter키가 눌릴 때만 실행됩니다.
모든 키 수식어
- .enter
- .tab
- .delete(백스페이스와 Delete키)
- .esc
- .space
- .up, .down, .left, .right
6. 컴포지션 API와 이벤트 처리
Composition API를 사용하면 이벤트 핸들러를 setup함수에서 정의할 수 있습니다.
예제: setup함수에서 이벤트 핸들러 정의
<template>
<button @click="hadleClick">클릭</button>
</template>
<script>
import { definComponent } from 'vue';
export default defineComponent({
setup(){
const handleClick = () => {
alert('Composition API에서 처리된 클릭 이벤트');
};
return { hadleClick };
}
});
</script>
★ Vue SFC Playground 코드 실행 →
7. 이벤트 버스
Vue3에서는 이벤트 버스(event bus)를 직접적으로 사용하지 않고, emit과 같은 컴포넌트간 통신 방식을 활용합니다.
자식 -> 부모 이벤트 전달 (emit 사용)
<!-- parent.vue -->
<template>
<child @custom-event="handleCustomWEvent"/>
</template>
<script>
import child from './child.vue';
export default {
component: {child},
methods: {
handleCustomEvent(payload){
alert('자식으로부터 전달된 데이터:', prelaod);
},
},
};
</script>
<!-- Chlde.vue -->
<template>
<button @click="emitEvent">이벤트 보내기</button>
</template>
<script>
export default {
emit: ['custom-event'],
methode:{
emitEvent(){
this.$emi('custom-event', {message: 'Hello Parent!'});
},
},
};
</script>
★ Vue SFC Playground 코드 실행 →
요약
1. v-on 또는 @를 사용해 이벤트 리스너를 추가할 수 있습니다.
2. 다양한 수식어(.stop, .prevent, .once 등)를 사용해 이벤트 동작을 제어할 수 있습니다.
3. Composition API에서는 setup 함수 내부에서 이벤트 핸들러를 정의하고, ref나 reactive 데이터를 활용할 수 있습니다.
4. 이벤트는 컴포넌트 간 데이터 전달과 UI 상호 작용을 간단하게 구현하는 핵심도구입니다.
'Vue.js 3 주요 문법 (vue:)' 카테고리의 다른 글
| vue: Watch와 WatchEffect (0) | 2024.11.26 |
|---|---|
| vue: 양방향 바인딩(v-model) (0) | 2024.11.22 |
| vue: Drective (0) | 2024.11.20 |
| vue: Class와 Style 바인딩 (0) | 2024.11.19 |
| vue: 조건부 렌더링 (v-if, v-show) (0) | 2024.11.18 |