[Vue] emit 사용하기

C____JIN·2022년 12월 1일
0

Vue

목록 보기
5/6
post-thumbnail

자식 컴포넌트의 변수로 부모 컴포넌트의 메서드를 동작시키고 반환 값을 다시 자식 컴포넌트로 가져오는 방법이 있다.

부모 컴포넌트

<template>
  <ChildComponent 
		@up="increase"
  />
</template>
<script>
import ChildComponent from '@/ChildComponent.vue';

export default {
	setup() {
      const increase = (count) = > {
        count += 1;
      };
      
      return {
        increase,
      }
    },
  	components: {
      ChildComponent,
    }
}
</script>

자식 컴포넌트에 up이라는 이름으로 increase 메서드 전달

자식 컴포넌트

<template>
  <p> {{ count }} </p>
  <button @click="clickToIncrease(count)">CLICK</button>
</template>
<script>
export default {
	emits: ['up',],
	
	setup(context){
      const count = ref(0);
      
      const clickToIncrease = (count) => {
        context.emit('up', count);
      };
      
      return {
        count,
      }
    }
}
</script>

emits로 부모 컴포넌트에서 전달 받고 clickToIncrease 메서드를 통해 부모 컴포넌트의 메서드를 동작시키고 값을 반환해서 출력한다.

profile
개발 블로그🌐 개발일지💻

0개의 댓글