[개발] 프로그램 지식

Vue 이벤트 수정자: 완벽 가이드

  • -
반응형
Vue 이벤트 수정자: 완벽 가이드

Vue 이벤트 수정자: 완벽 가이드

Vue 이벤트 수정자란?

Vue의 이벤트 수정자는 이벤트가 메소드 실행을 트리거하는 방법을 수정하고, 보다 효율적이고 간단한 방법으로 이벤트를 처리하는 데 도움이 됩니다. 이벤트 수정자는 Vue 지시어와 함께 사용됩니다 v-on. 예를 들면 다음과 같습니다:

  • HTML 양식의 기본 제출 동작 방지(v-on:submit.prevent)
  • 페이지가 로드된 후 이벤트가 한 번만 실행되도록 설정(v-on:click.once)
  • 메소드를 실행하기 위한 키보드 키 지정(v-on:keyup.enter)

v-on 지시문을 수정하는 방법

<div id="app">
  <p>Click the button to create an alert:</p>
  <button v-on:click.once="createAlert">Create Alert</button>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    methods: {
      createAlert() {
        alert("Alert created from button click")
      }
    }
  })
  app.mount('#app')
</script>

키보드 키 이벤트 수정자

세 가지 키보드 이벤트 유형이 있습니다: keydown, keypress, keyup. 각 키 이벤트 유형을 사용하면 키 이벤트가 발생한 후 수신할 키를 정확하게 지정할 수 있습니다. 예를 들어 .space, .enter, .w 등이 있습니다.

예제

<div id="app">
  <input v-on:keydown="getKey">
  <p>{{ keyValue }}</p>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        keyValue: ''
      }
    },
    methods: {
      getKey(event) {
        this.keyValue = event.key
        console.log(event.key)
      }
    }
  })
  app.mount('#app')
</script>

마우스 버튼 수정자

마우스 클릭에 반응하려면 v-on:click을 쓸 수 있지만, 클릭한 마우스 버튼을 지정하려면 .left, .center, .right 수정자를 사용할 수 있습니다.

예제

<div id="app">
  <div v-on:click.right="changeColor"
       v-bind:style="{backgroundColor:'hsl('+bgColor+',80%,80%)'}">
    <p>Press right mouse button here.</p>
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        bgColor: 0
      }
    },
    methods: {
      changeColor() {
        this.bgColor += 50
      }
    }
  })
  app.mount('#app')
</script>

키보드 이벤트 수정자 결합

이벤트 수정자를 조합하여 둘 이상의 작업이 동시에 발생해야 메소드를 호출하도록 설정할 수 있습니다.

예제

<div id="app">
  <p>Try pressing the 's' key:</p>
  <textarea v-on:keydown.ctrl.s="createAlert"></textarea>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    methods: {
      createAlert() {
        alert("You pressed the 'S' and 'Ctrl' keys, in combination!")
      }
    }
  })
  app.mount('#app')
</script>

마우스 버튼과 .prevent 수정자

.prevent 수정자를 사용하여 마우스 오른쪽 버튼을 클릭할 때 기본 드롭다운 메뉴가 표시되는 것을 방지할 수 있습니다.

예제

<div id="app">
  <div v-on:click.right.prevent="changeColor"
       v-bind:style="{backgroundColor:'hsl('+bgColor+',80%,80%)'}">
    <p>Press right mouse button here.</p>
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        bgColor: 0
      }
    },
    methods: {
      changeColor() {
        this.bgColor += 50
      }
    }
  })
  app.mount('#app')
</script>

클릭 시 Shift 키 사용 예제

아래 예제는 사용자가 'Shift' 키를 누르면서 이미지를 클릭할 때 이미지를 변경하는 방법을 보여줍니다.

<div id="app">
  <p>Press the 'Shift' keyboard key while you do a left mouse button click on the image below to change it.</p>
  <img v-on:click.left.shift="changeImg" v-bind:src="imgUrl">
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        imgUrlIndex : 0,
        imgUrl: 'img_tiger_square.jpeg',
        images: [
          'img_tiger_square.jpeg',
          'img_moose_square.jpeg',
          'img_kangaroo_square.jpeg'
        ]
      }
    },
    methods: {
      changeImg() {
        this.imgUrlIndex++;
        if(this.imgUrlIndex>=3){
          this.imgUrlIndex=0
        }
        this.imgUrl = this.images[this.imgUrlIndex]
      }
    }
  })
 app.mount('#app')
</script>

이 글이 유용했다면 좋아요와 공유 부탁드립니다! 더 많은 웹 개발 관련 정보는 저희 블로그에서 확인하세요.

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.