ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • emit 개념 관련 정리
    VUE.JS 2020. 4. 30. 14:34

    하위 컴포넌트의 메서드에서 상위 컴포넌트로 통신하는 방법은 VUE에서 emit을 사용한다.

    아래 소스와 결과를 보면 쉽게 이해가 가능하다.

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        
        <div id="app">
            <p>{{ num }}</p>
     
            <!-- $emit('pass')를 이용해서 상위 컴포넌트의 logText 메서드 호출-->
            <app-header v-on:pass="logText"></app-header>    
            <!-- $emit('add')를 이용해서 상위 컴포넌트의 increaseNumber 메서드 호출-->
            <app-content v-on:add="increaseNumber"></app-content>    
        </div>
     
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script>
     
     
            //하위 컴포넌트 app Header에서 클릭 이벤트 발생 (emit 사용) 
            var appHeader = {
                template  : '<button v-on:click="passEvent">Click</button>',
                methods : {
                    passEvent :function() {
                        this.$emit('pass');
                    }
                }
            }
            //하위 컴포넌트 app Content에서 클릭 이벤트 발생 (emit 사용) 
            var appContent = {
                template : '<button v-on:click="addNumber">add</button>',
                methods : {
                    addNumber : function() {
                        this.$emit('add');
                    }
                }
            }
     
            new Vue({
                el : "#app",
                components : {
                    'app-header' : appHeader,
                    'app-content' : appContent,
                },
                data() {
                    return {
                        num : 0
                    }
                },
                methods : {
                    logText : function() {
                        console.log('hi');
                    },
                    increaseNumber : function() {
                        this.num = this.num + 1;
                    }
     
                }
     
            });
        </script>
    </body>
    </html>
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

    결과 

     

Designed by Tistory.