본문 바로가기

Front-end/Vue

Vue.js) 컴포넌트 - Emit

1. Emit

Vue.js의 emit은 부모-자식 컴포넌트 간의 통신을 처리하는 중요한 메커니즘입니다. 자식 컴포넌트에서 이벤트를 발생시키고, 부모 컴포넌트가 해당 이벤트를 수신하여 처리할 수 있습니다. 이를 통해 부모 컴포넌트와 자식 컴포넌트 간의 데이터 흐름을 관리할 수 있습니다.

 

2. 부모 컴포넌트에서 메서드 상속

// App.vue
<template>
	<MyBtn @parent_event="parent_event" />
</template>

<script>
import MyBtn from './components/MyBtn.vue';
export default {
	components: {
		MyBtn,
	},
	methods: {
		parent_event() {
			console.log('parent event!');
		},
	},
};
</script>

// MyBtn.vue
<template>
	<h1 @click="$emit('parent_event')">parent</h1>
</template>

<script>
export default {
	inheritAttrs: false,
	emits: ['parent_event'],
};
</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>

emits 속성에 부모 컴포넌트에서 상속하는 함수명을 배열형식으로 정의해 주고 이벤트를 호출할 엘리먼트에서
@['event']="$emit(["parent event"])" 라고 명시하면 됩니다.

 

2. 부모 컴포넌트에서 매개변수 있는 메서드 상속

// App.vue
<template>
	<MyBtn @click="log" />
</template>

<script>
import MyBtn from './components/MyBtn.vue';
export default {
	components: {
		MyBtn,
	},
	methods: {
		log(msg, e) {
        	console.log(e)
			console.log('Click!');
		},
	},
};
</script>

// MyBtn.vue
<template>
	<h1 @click="$emit('click', 'HelloWorld', $event)">parameter</h1>
</template>

<script>
export default {
	inheritAttrs: false,
	emits: ['click'],
};
</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>

위처럼 매개 변수가 존재하는 함수를 호출할 때는 
@["event"]=$emit(["parent event"], ["parameter1"],..... , ["parameter3"]) 이런 식으로 표현할 수 있습니다. event 객체를 호출할 때는 이전과 동일하게 $event로 불러올 수 있습니다.

 

3. 부모 컴포넌트에서 자식 컴포넌트 data 값 불러오기

// App.vue
<template>
	<MyBtn
		@change-msg="logMsg" />
</template>

<script>
import MyBtn from './components/MyBtn.vue';
export default {
	components: {
		MyBtn,
	},
	methods: {
		logMsg(msg) {
			console.log(msg);
		},
	},
};
</script>

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

<script>
export default {
	inheritAttrs: false,
	emits: ['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>

console 창에 매개변수로 받은 msg를 console에 출력하는 코드입니다. 자식 컴포넌트에서 changeMsg 메서드를 상속받고양방향 바인딩 v-model을 사용하여 입력 필드에 변화가 발생하면 msg가 업데이트되고 watch 속성으로 변화가 감지될 때마다 changeMsg 함수에 변화가 발생한 msg를 매개변수로 전달합니다.

 

참고 문서:

https://v2.ko.vuejs.org/v2/guide/components-custom-events.html

'Front-end > Vue' 카테고리의 다른 글

Vue.js) 컴포넌트 - Provide, Inject  (0) 2024.07.30
Vue.js) 컴포넌트 - Slot  (3) 2024.07.30
Vue.js) 컴포넌트 - 속성 상속  (2) 2024.07.29
Vue.js) 컴포넌트-기초  (0) 2024.07.29
Vue.js) v-model 수식어  (1) 2024.07.29