Front-end/Vue

Vue.js) 컴포지션 API - props, context

ljs981026 2024. 8. 1. 14:43

1. props, context

  • props: 부모 컴포넌트에서 자식 컴포넌트로 전달되는 데이터입니다. 자식 컴포넌트는 전달받은 props를 통해 부모 컴포넌트와 데이터를 공유합니다.
  • context: 컴포넌트의 전체적인 문맥을 나타내며, 주로 attrs, slots, emit 등의 속성을 포함합니다.

2. 컴포지션 API props, context 사용

// App.vue
<template>
	<MyBtn class="parent" style="color: red" @hello="log">Hello</MyBtn>
</template>

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

자식 컴포넌트 MyBtn에 parent 클래스, style 속성, log 메서드를 상속을 합니다.

// MyBtn.vue
<template>
	<div v-bind="$attrs" class="btn" @click="hello">
		<slot></slot>
	</div>
</template>

<script>
import {onMounted} from 'vue';
export default {
	inheritAttrs: false,
	props: {
		color: {
			type: String,
			default: 'gray',
		},
	},
	setup(props, context) {
		const hello = () => {
			context.emit('hello');
		};
		onMounted(() => {
			console.log(props.color);
			console.log(context.attrs);
		});
		return {
			hello,
		};
	},
};
</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>

setup 속성에 props와 context를 매개 변수로 하여 불러옵니다. 여기서 주의해야 할 점은 attrs, emit은 기존에 불러오던 방식, $ 기호를 붙여 사용하는 것과 달리 setup 내부에서 호출할 때는 $ 기호 없이 사용해야 합니다.

컴포지션 API를 사용하지 않으면 코드는 아래와 같다.

// MyBtn.vue
<template>
	<div v-bind="$attrs" class="btn" @click="hello">
		<slot></slot>
	</div>
</template>

<script>
export default {
	inheritAttrs: false,
	props: {
		color: {
			type: String,
			default: 'gray',
		},
	},
    emits: ['hello'],
    mounted() {
   		console.log(this.color);
        console.log(this.$attrs);
    },
    methods: {
    	hello() {
     		this.$emit('hello')   
        }
    },
};
</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>

 

참고 문서:

https://ko.vuejs.org/api/composition-api-setup.html#accessing-props