써치킴의 우당탕탕 개발 블로그

[Vue.js][Ch2][Vue 문법] 이벤트 핸들링 본문

완벽하게 Vue.js

[Vue.js][Ch2][Vue 문법] 이벤트 핸들링

써치킴 2022. 4. 7. 04:02

v-on 디렉티브는 @기호, DOM 이벤트를 듣고 트리거 될 때와 JavaScript를 실행할 때 사용한다.
v-on:click="methodName" 을 줄여서 @click="methodName"으로 사용한다.

 

App.vue

<template>
  <button @click="handler"> <!-- vue.js는 소괄호()를 생략할 수 있다.  -->
    Click 1
  </button>
  <button @click="handler">
    Click 2
  </button>
</template>

<script>
export default {
  methods: {
    // event : 이벤트 정보를 갖고있는 데이터
    // 단순히 첫번째 들어오는 데이터를 받아주는 역할이기 때문에
    // e, ev 등으로 바꿔서 사용 가능
    handler(event) {  
      console.log(event);
      console.log(event.target);   
      console.log(event.target.textContent);   
    }
  }
}
</script>

메소드의 event 인수

이벤트 정보를 갖고있는 데이터

단순희 첫번째 들어오는 데이터를 받아주는 역할이기 때문에 e, ev 등으로 바꿔서 사용 가능

 

출력

메소드에 인수, 이벤트 객체를 같이 사용할 수 있다.

App.vue

<template>
  <button @click="handler('hi')"> 
    Click 1
  </button>
  <button @click="handler2('what', $event)">  <!-- 인수, 이벤트 객체 둘다 필요할 때 -->
    Click 2
  </button>
</template>

<script>
export default {
  methods: {
    handler(msg) {    // 메소드에 인수를 넣어주면 넣어진 매개변수로 받아진다.
      console.log(msg);
    },
    handler2(msg, event){
      console.log(msg);
      console.log(event);
    }
  }
}
</script>

출력

하나의 이벤트에 여러개의 함수를 동시에 사용할 수 있다.

이 때는 '호출하겠다'라는 의미로 소괄호를 사용해야 한다!

 

App.vue

<template>
  <button @click="handlerA(), handlerB()"> <!-- 하나의 이벤트에 여러개의 메소드를 사용할 수 있다. -->
    Click me!
  </button>
</template>

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

출력

Comments