Vue

[Vue] 이벤트(Event)

yangjoy 2021. 9. 12. 19:14

1 이벤트


이벤트란?

    <div id="app">
        <button onclick="alert('hello world')">Click Me</button>
    </div>

보통 자바스크립트로 줄 때는 이런 형식으로 이벤트를 줄 수 있다. 그렇다면 뷰에서는??

 

    <div id="app">
        <button v-on:click="alertFunc">Click Me</button>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
             
            },
            methods: {
                alertFunc(){
                  alert('hi seyoung');
              }
            }
        })
    </script>

결과값 :

 

v-on: 지시어를 이용해서 자바스크립트 이벤트를 사용할 수 있다.

 

 

2 이벤트 응용


버튼을 누르면 숫자에 1씩 더하고 뺄 수 있는 이벤트

    <div id="app">
        {{year}}
        <button v-on:click="plus">더하기</button>
        <button v-on:click="minus">빼기</button>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                year: 2021
            },
            methods: {
                plus(){
                    this.year++;

                },
                minus(){
                    this.year--;
                }
            }
        })
    </script>

결과값 :

클릭 이벤트를 이용해서 plus 함수를 눌렀을 때는 년도가 올라가고

minus 버튼을 누르면 년도가 내려가도록 이벤트를 설정할 수 있다.

 

 


 

제출했을 때 알림창으로 'submitted!'를 알려주는 이벤트

    <div id="app">
        <form v-on:submit="submit">
            <input type="text"><br>
            <button type="submit">Submit</button>
        </form>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                year: 2021
            },
            methods: {
                submit(){
                    alert('submitted!');
                }
            }
        })
    </script>

결과값 :

 

3 이벤트 수식어


event.preventDefalut() 같은 메서드를 사용해줄 때 수식어를 이용할 수 있다.

v-on:click.prevent

 

    <div id="app">
        <button v-on:click.prevent="greeting()">인사하다</button>
        <button v-on:click.prevent="what()">무엇을?</button>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
            },
            methods: {
                greeting(){
                    alert('안녕!');
                },
                what(){
                    alert('뭐임마!');
                }
            }
        })
    </script>

홈페이지를 확인하면 다양한 지시어 확인이 가능하다.

 

Event Handling — Vue.js

Vue.js - The Progressive JavaScript Framework

vuejs.org

  • .stop
  • .prevent
  • .capture
  • .self
  • .once
  • .passive