Front-end/Vue
Vue.js) 이벤트 핸들링
ljs981026
2024. 7. 26. 11:01
1. 이벤트 핸들링
v-on 디렉티브를 사용하여 DOM 이벤트를 듣고 트리거 될 때 JavaScript를 실행할 수 있습니다.
2. 사용 예제
- 이벤트 출력
<template>
<button @click="handler">Click1</button>
</template>
<script>
export default {
methods: {
handler(event) {
console.log(event);
console.log(event.target);
},
},
};
</script>
위 사진과 같이 해당 event와 관련된 속성들이 담긴 event 객체와 event.target으로 해당 event가 등록되어 있는 엘리먼트가 출력됨을 알 수 있습니다.
* 매개변수는 event외에도 임의로 설정해도 event객체를 불러올 수 있습니다. ex) e
* v-on:['event'] 형식은 @:['event'] 형식으로 축약해서 사용할 수 있습니다.
- 매개변수와 이벤트를 동시에 출력
<template>
<button @click="handler('hi', $event)">Click1</button>
</template>
<script>
export default {
methods: {
handler(msg, event) {
console.log(msg);
console.log(event);
},
},
};
</script>
이벤트 함수를 호출할 때 매개변수와 이벤트를 같이 출력하고 싶을 때 위와 같이 ('매개변수',..., $event) 호출하면 event 객체를 받아올 수 있습니다.
- 이벤트 함수 동시 호출
<template>
<button @click="handlerA(), handlerB()">Click1</button>
</template>
<script>
export default {
methods: {
handlerA() {
console.log('A');
},
handlerB() {
console.log('B');
},
},
};
</script>
이벤트 함수에 위와같이 함수를 여러 개 호출할 수 있습니다. 호출할 땐 , (쉼표)로 구분하고 매개변수가 없더라도 소괄호를 꼭 표시해주어야 합니다.
참고 문서: