context
context란 setup(props, context) 함수의 두 번째 인자로 전달되는 객체로 컴포넌트 내부에서 this 없이 접근해야 하는 추가적인 속성들과 메서드를 제공한다.
1. attrs: 부모 컴포넌트로부터 전달받았지만 props로 정의되지 않은 모든 attribute(HTML 속성)를 담는 객체다. 즉, v-bind="$attrs"와 같이 템플릿에 바인딩할 때 사용한다. 기존 Options API의 this.$attrs에 해당한다.
2. emit: 자식 컴포넌트에서 부모로 이벤트를 발생시킬 때 사용하는 함수다. 기존 this.$emit과 동일한 역할을 하며, context.emit('event이름', payload) 형태로 사용한다.
3. slot: 자식 컴포넌트에 전달된 slot 콘텐츠에 접근할 수 있는 객체다. this.$slots와 동일하다.
4. expose: (Vue 3.2 이상) 컴포넌트 인스턴스에서 setup에서 선언한 속성이나 메서드를 명시적으로 노출할 때 사용하는 함수다. 일반적으로 <script setup> 문법에서 주로 사용된다.
setup(props, { attrs, slots, emit, expose }) { ... } 이렇게도 사용 가능.
<script>
import { computed } from 'vue';
export default {
props: ['firstName', 'lastName', 'age'],
setup(props, context) {
const uName = computed(function() {
return props.firstName + ' ' + props.lastName;
};
console.log(context);
context.emit('save-data', 1); // this.$emit('save-data', 1);
// context.attrs: 추가 전달된 HTML 속성
// context.slots: 슬롯 콘텐츠
// context.emit: 부모로 이벤트 전달
// context.expose: 인스턴스에 노출할 속성/메서드 지정
return { userName: uName };
}
}
</script>
provide, inject
provide(보내는 쪽)
import { ref, provide } from 'vue';
export default {
setup() {
const uAge = ref(31);
provide('userAge', uAge);
}
inject (받는 쪽)
<script>
import { computed, inject } from 'vue';
export default {
props: ['firstName', 'lastName',],
setup(props, context) {
const uName = computed(function() {
return props.firstName + ' ' + props.lastName;
};
const age = inject('userAge');
return { userName: uName, age };
}
}
</script>'Vue' 카테고리의 다른 글
| Vue3 : Composition API(생명주기 훅) (0) | 2025.08.19 |
|---|---|
| Vue3 : Composition API (methods, computed, watch) (0) | 2025.08.01 |
| Vue3 : Composition API (ref, reactive) (1) | 2025.07.31 |