Front-end/Vue

[Vue] vue3 script setup defineExpose 값 받기

냐옹멍멍 2024. 1. 4. 17:02
반응형

# 이슈

까지는 아니고.. script setup에서 defineExpose로 올린 값을 부모에서 참조하는 법이다

vue에서 ref로는 컴포넌트 또는, 엘리먼트도 참조 할 수 있다는 점을 이용한다.

 

# 방안

vue에서 ref로는 컴포넌트 또는, 엘리먼트도 참조 할 수 있다는 점을 이용한다.

 

부모 컴포넌트 

<!-- parent.vue -->
<script setup>
	...
	const child = ref(null)
	...
    console.log(child.value) // child 컴포넌트 확인
</script>
<template>
	...
	<child-component ref="child" />
	...
</template>

 

 

자식 컴포넌트

<!-- child-component.vue -->
<script setup>
	...
    const exposeData = ref('hi~')
    const normalData = ref('hello~~') // 이건 안함
    ...
	defineExpose({
    	exposeData // 이 데이터만 상위로 expose한다
    })
</script>
...

 

다른 데이터는 두고 exposeData만 defineExpose 해보자

'exposeData'가 출력된다.

 

# 참고

https://stackoverflow.com/questions/73344760/defineexpose-from-components-script-setup-not-working-in-vue-3

반응형