본문 바로가기
개인공부/Vue3

Vue3 #8

by BTSBRINGMEHERE 2023. 11. 30.

서론

Function props가 문제가 아직 있다고해서 emit에서 해결이 가능하다고 합니다.

*사실 문제는 없는데 개발자들 사이에서 이야기가 나오고 있다고합니다 ㅎㅎㅎ

 

본론

emit

컴포넌트에서 이벤트를 발생(emit)시킬 수 있는 사용자 지정 이벤트 목록/해시 입니다.

배열 기반의 단순한 문법과 이벤트 유효성 검사를 구성할 수 있는 객체 기반의 문법이 있습니다.

<script setup>
/*
자식은 이름을 지어서 내보낸다.
부모는 그 이름으로 받아서 함수를 실행시킨다.
*/
import { ref } from "vue";
import HelloWorld from "./components/HelloWorld.vue";

let NumberData = ref(3);
</script>

<template>
  <HelloWorld :PropsData="NumberData" @IncreaseOne="NumberData++" />
</template>

/* HelloWorld.vue */
<script setup>
import { defineProps, defineEmits } from "vue";

const props = defineProps({
  PropsData: {
    type: Number,
    required: true,
    default: 0,
  },
});

const emits = defineEmits({
  IncreaseOne: null,
});
</script>

<template>
  <button @click="$emit('IncreaseOne')">{{ props.PropsData }}</button>
</template>

 

props와 다르게 함수를 prop으로 받아와서 부모 컴포넌츠에서 변화를 주어서 자식 컴포넌츠에게 변화된 값을 보내는데

emits는 부모 컴포넌츠에서 받아온 prop을 자식 컴포넌츠에서 변화를 주워서 부모 컴포넌츠에게 변화된 값을 보냅니다.

<script setup>
import { ref } from "vue";
import HelloWorld from "./components/HelloWorld.vue";

let NumberData = ref(5);
const IncreaseOne = (payload) => {
  NumberData.value += payload;
};
</script>

<template>
  <HelloWorld :PropsData="NumberData" @IncreaseByAmount="IncreaseOne" />
</template>

/* HelloWorld.vue */
<script setup>
import { defineProps, defineEmits } from "vue";

const props = defineProps({
  PropsData: {
    type: Number,
    required: true,
    default: 0,
  },
});

/* emit 설정 및 유효성 검사 */
const emits = defineEmits({
  IncreaseByAmount: (element) => {
    if (typeof element === "number" && element > 0) return true;
    else return false;
  },
});

/* 간단한 value를 보낼 때 */
const emitMethod = () => {
  emits('IncreaseByAmount', 5)
}

/* 간단한 객체를 보낼 때 */
const emitMethods = () => {
  const payload = {
    foo: "안녕",
    bar: "하세요",
    val: 1
  }
  emits('IncreaseByAmount', payload)
}
</script>

<template>
  <button @click="$emit('IncreaseByAmount', 5)">{{ props.PropsData }}</button>
  <button @click="emitMethod">{{ props.PropsData }}</button>
</template>

/*
  defineEmits를 통해 유효성검사를 할 수 있지만 기능은 실행이되고 콘솔창에서 주의만 줍니다.
  emit을 통해 자식에서 보낸 값 "5"를 부모 컴포넌츠에서 받아서 기존 값에서 +5가 되는 모습입니다.
  마크업 부분에서 emit을 사용하면 코드가 보기 불편해 집니다. 함수를 생성해서 저런식으로 만들면 됩니다.
  참고로 숫자 5가 아니라 객체형태로 보낼 수도 있습니다.
*/

위의 코드와 같이 사용하면 emit을 사용하는데 큰 어려움을 없을 것 같습니다.

 

정리

emit을 주로 사용할 것 같습니다.

다음에는 v-model과 emits을 동시에 사용하는 법을 배울 것 입니다.

'개인공부 > Vue3' 카테고리의 다른 글

Vue3 #10  (2) 2023.12.05
Vue3 #9  (2) 2023.12.01
Vue3 #7  (0) 2023.11.30
Vue3 #6  (0) 2023.11.29
Vue3 #5  (1) 2023.11.27