Frontend/Vue 2

vue3 component emit

SOLYI 2021. 10. 19. 13:38
//App.vue
<template>
  <!-- @이름은 뭐든 상관없다! -->
  <MyBtn
    @heropy="log"
    @change-msg="logMsg">      
    <!-- changeMsg (X)
     change-msg (O) -->
    Banana
  </MyBtn>
</template>

<script>
import MyBtn from '~/components/MyBtn'
export default {
  components:{
    MyBtn
  },
  methods:{
    log(e){
      console.log('click~')
      console.log(e)         //$emit('heropy', 이부분)
    },
    logMsg(msg){
      console.log(msg)
    }
  }
}
</script>

 

//MyBtn.vue
<template>
  <div class="btn">
    <slot></slot>
  </div>
  <h1 @dblclick="$emit('heropy', $event)">
    <!-- 이름 emits 내부와 동일하게 -->
    ABC button
  </h1>

  <input
    type="text"
    v-model="msg" />
</template>

<script>
export default {
  emits:[
    'heropy',
    'changeMsg'
    // App.vue의 이름과 동일하게
  ],
  data(){
    return{
      msg: ''
    }
  },
  watch:{
    msg(){
      this.$emit('changeMsg', this.msg)
    }
  }
}
</script>

<style scoped>
  .btn{
    display: inline-block;
    margin: 4px;
    padding:6px 12px;
    border-radius: 4px;
    background-color:grey;
    color: white;
    cursor: pointer;  
  }
</style>
반응형