Vue 컴포넌트 이벤트

정현승·2025년 1월 8일

이벤트 발생 및 수신

$emit : 자식 컴포넌트에서 이벤트를 발생시켜 부모 컴포넌트에 신호를 보냅니다.

<!-- Child.vue -->
<template>
  <button @click="$emit('custom-event', 'Hello from Child!')">Click Me</button>
</template>

<script>
export default {
  emits: ["custom-event"], // 정의된 이벤트
};
</script>

@ : 부모 컴포넌트에서 자식 컴포넌트의 이벤트를 리스닝합니다.

<!-- Parent.vue -->
<template>
  <Child @custom-event="handleCustomEvent" />
</template>

<script>
import Child from './Child.vue';

export default {
  components: { Child },
  methods: {
    handleCustomEvent(message) {
      alert(message); // "Hello from Child!"
    },
  },
};
</script>

이벤트 인수

$emit에 추가 인수를 전달할 수 있습니다

<!-- 자식 컴포넌트 (Child.vue) -->
<template>
  <button @click="$emit('custom-event', 'Hello', 42)">Click Me</button>
</template>

<script>
export default {
  emits: ['custom-event'],
};
</script>
<!-- 부모 컴포넌트 (Parent.vue) -->
<template>
  <Child @custom-event="handleEvent" />
</template>

<script>
import Child from './Child.vue';

export default {
  components: { Child },
  methods: {
    handleEvent(message, number) {
      console.log(message); // 출력: "Hello"
      console.log(number);  // 출력: 42
    },
  },
};
</script>

이벤트 유효성 검사

prop 타입 유효성 검사와 마찬가지로, 배열 구문 대신 객체 구문으로 정의된 이벤트는 유효성 검사가 가능합니다.

export default {
  emits: {
    // 유효성 검사 없음
    click: null,

    // submit 이벤트 유효성 검사
    submit: ({ email, password }) => {
      if (email && password) {
        return true
      } else {
        console.warn('Invalid submit event payload!')
        return false
      }
    }
  },
  methods: {
    submitForm(email, password) {
      this.$emit('submit', { email, password })
    }
  }
}

0개의 댓글