OptionsAPI와 차이점
📌 기존 OptionsAPI를 이용해서 자식 컴포넌트의 메소드를 호출하는 방법은 " 더보기 " 를 눌러보자 : )
더보기
ex) 부모 컴포넌트에서
<template>
<div>
<ChildComponent ref="myChild" />
</div>
</template>
<script>
import ChildComponent from '@/views/ChildComponent.vue'
export default {
components : {
ChildComponent
},
mounted() {
this.$refs.myChild.showAlert()
},
}
</script>
ex) 자식 컴포넌트에서
<template>
<div></div>
</template>
<script>
export default {
methods: {
showAlert() {
alert('hello')
}
},
}
</script>
공통점
접근하고 싶은 컴포넌트 태그에 ref 속성을 사용한다.
차이점
스크립트 태그에서 this.$refs.ref속성값 대신 ref()함수로 선언된 변수명을 자식 컴포넌트의 ref 속성값으로 사용해야하고,
*. 따라서 ref 속성값에 사용될 변수가 필요하다.
그리고, 자식 컴포넌트에서 defineExpose({ })를 사용해야한다.
사용 예시
부모 컴포넌트
<template>
<div>
<!-- 순서[2] - refName1의 변수엔 해당 컴포넌트가 할당된다 -->
<ChildComponent ref="refName1" />
</div>
</template>
<script setup>
import ChildComponent from '@/views/ChildComponent.vue'
import { ref, onMounted } from 'vue';
const refName1 = ref() // 순서[1] - <ChildComponent ref="refName1" /> 에서 사용될 변수명
onMounted(() => {
// 순서[3] - ChildComponent 태그에 적힌 defineExpose 별칭중에서 showAlert을 사용한다
refName1.value.showAlert()
})
</script>
자식 컴포넌트
<template>
<div></div>
</template>
<script setup>
/* eslint-disable */
const showAlert = () => {
alert('hello')
}
/* ==================================================================
#. defineExpose 사용법
defineExpose({'부모컴포넌트에서 사용할 별칭' : 실행될함수})
별칭주기 번거롭다면 실행될 함수명 그대로 별칭으로 쓸 수도 있다 .
▼ 함수명 그대로 별칭으로 쓰는 예시 */
defineExpose({showAlert}) // defineExpose({'showAlert', showAlert})이랑 같은 내용인데 축약버전
</script>
'💻 FullStack > Vue.js' 카테고리의 다른 글
Vue 시작일과 종료일로 진행률(%) 표시하기 (0) | 2023.09.19 |
---|---|
Vue CSS height 속성 값에 % 사용해보기 (1) | 2023.09.14 |
Vue.js 코드 작성할 수 있는 사이트 소개 (Playground) (0) | 2023.08.21 |
데이터 시각화 - Chart.js 라이브러리 (0) | 2023.08.20 |
Composition API 방식에서 emit, props를 쓰고싶다면 (0) | 2023.08.12 |