ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Vue.js 문법 - 컴포넌트 Emit
    Vue/Vue.js 문법 2021. 7. 16. 02:54

     

    Emit - 이벤트를 상속

     

    App.vue

    <template>
      <MyBtn @click="log">
        Banana
      </MyBtn>
    </template>
    <script>
    import MyBtn from '~/components/MyBtn'
    
    export default {
      components: {
        MyBtn
      },
      methods: {
        log() {
          console.log('Click!!')
        }
      }
    }
    </script>

     

    MyBtn.vue

    <template>
      <div class="btn 1">
        <slot></slot>
      </div>
      <div
        @click="$emit('click')"
        class="btn 2">
        <slot></slot>
      </div>
    </template>
    <script>
    export default {
      emits: [
        'click'
      ]
    }
    </script>

     

    결과

     

    코드 이해하기

    - 자식 컴포넌트(MyBtn.vue) 최상위 요소가 2개이므로 속성 상속이 적용되지 않음

    - 즉, 부모 컴포넌트(App.vue)의 @click 이벤트가 동작하지 않음

    - 이벤트를 직접 연결하기 위해 emit 을 사용

    - emits 옵션 추가, 부모 컴포넌트 이벤트(click)를 명시

    - <template> @click="$emit('click')" 작성하면 부모 요소의 연결되어 있는 이벤트와 연결

    - 예제 결과에서 오른쪽 버튼을 누를때만 동작 (부모 컴포넌트 메소드 log() 동작)

     

    <!-- App.vue -->
    <MyBtn @ITBlue="log">
    
    <!-- MyBtn.vue -->
    @click="$emit('ITBlue')"
    
    emits: [
      'ITBlue'
    ]

    - click이 아닌 원하는 이름의 이벤트를 자유롭게 만들어 사용할 수도 있다

     

    Emit을 활용한 양방향 데이터 바인딩 예제

     

    <!-- App.vue -->
    
    <template>
      <MyBtn
        @ITBlue="log"
        @change-msg="logMsg">
        Banana
      </MyBtn>
    </template>
    
    <script>
    import MyBtn from '~/components/MyBtn'
    
    export default {
      components: {
        MyBtn
      },
      methods: {
        log(event) {
          console.log('Click!!')
          console.log(event)
        },
        logMsg(msg) {
          console.log(msg)
        }
      }
    }
    </script>

     

    <!-- MyBtn.vue -->
    
    <template>
      <div class="btn 1">
        <slot></slot>
      </div>
      <div
        @dblclick="$emit('ITBlue', $event)"
        class="btn 2">
        <slot></slot>
      </div>
      <input
        type="text"
        v-model="msg" />
    </template>
    
    <script>
    export default {
      emits: [
        'ITBlue',
        'changeMsg'
      ],
      data() {
        return {
          msg: ''
        }
      },
      watch: {
        msg() {
          this.$emit('changeMsg', this.msg)
        }
      }
    }
    </script>
    
    <style scoped lang="scss">
      .btn {
        display: inline-block;
        margin: 4px;
        padding: 6px 12px;
        border-radius: 4px;
        background-color: gray;
        color: white;
        cursor: pointer;
      }
    </style>

     

    결과

     

    'Vue > Vue.js 문법' 카테고리의 다른 글

    Vue.js 문법 - Provide / Inject  (0) 2021.07.18
    Vue.js 문법 - 컴포넌트 Slot  (0) 2021.07.18
    Vue.js 문법 - 컴포넌트 속성 상속  (0) 2021.07.16
    Vue.js 문법 - 컴포넌트 기초  (0) 2021.07.16
    Vue.js 문법 - v-model 수식어  (0) 2021.07.15

    댓글

Designed by Tistory.