이벤트 핸들링

jude·2022년 2월 10일
0

vue

목록 보기
4/14
post-thumbnail

이벤트 핸들링

  • 이벤트 핸들러를 @click 디렉티브에 연결할 때 ()는 생략 가능
  • 핸들러 함수의 인자로 event 객체가 넘어옴
<template>
  <button @click="handler">click 1</button>
  <button @click="handler">click 2</button>
</template>

<script>
export default {
  methods: {
    handler(e) {
      console.log( e );
    }
  }
}

// console
PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0,}
</script>

  • 인자를 넣고 싶을 때 event 객체를 넘기는 방법은 $event를 넘김
<template>
  <button @click="handler('hi1', $event)">click 1</button>
  <button @click="handler('hi2', $event)">click 2</button>
</template>

<script>
export default {
  methods: {
    handler(msg, e) {
      console.log( msg, e );
    }
  }
}

// console
// click 1 클릭시
hi1
PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0,}

</script>

  • 하나의 요소에 이벤트 핸들러를 여러개 붙일 수 있다.
  • 이벤트 핸들러를 여러개 붙일 때는 ()를 생략하면 작동하지 않는다. ( 주의! )
<template>
  <button @click="handlerA(), handlerB()">click 1</button>
</template>

<script>
export default {
  methods: {
    handlerA() {
      console.log( 'A' );
    },
    handlerB() {
      console.log( 'B' );
    }
  }
}

// console
A
B
</script>
profile
UI 화면 만드는걸 좋아하는 UI개발자입니다. 프론트엔드 개발 공부 중입니다. 공부한 부분을 블로그로 간략히 정리하는 편입니다.

0개의 댓글