민우의 코딩일지
article thumbnail

 

 

 

 

1. OptionsAPI와 차이점

 

📌 기존 OptionsAPI를 이용해서 자식 컴포넌트의 메소드를 호출하는 방법은 " 더보기 " 를 눌러보자 : )

더보기

 

ex) 부모 컴포넌트에서

<html />
<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) 자식 컴포넌트에서

 

<html />
<template> <div></div> </template> <script> export default { methods: { showAlert() { alert('hello') } }, } </script>

 

 

 

공통점

접근하고 싶은 컴포넌트 태그에 ref 속성을 사용한다.

 

차이점

스크립트 태그에서 this.$refs.ref속성값 대신 ref()함수로 선언된 변수명을 자식 컴포넌트의 ref 속성값으로 사용해야하고,

*. 따라서 ref 속성값에 사용될 변수가 필요하다.

그리고, 자식 컴포넌트에서 defineExpose({  })를 사용해야한다.

 

 

 

 

 

 

 

 

2. 사용 예시

 

 

 

 

2.1. 부모 컴포넌트

 

 

<html />
<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>

 

 

 

 

 

2.2. 자식 컴포넌트

 

 

<html />
<template> <div></div> </template> <script setup> /* eslint-disable */ const showAlert = () => { alert('hello') } /* ================================================================== #. defineExpose 사용법 defineExpose({'부모컴포넌트에서 사용할 별칭' : 실행될함수}) 별칭주기 번거롭다면 실행될 함수명 그대로 별칭으로 쓸 수도 있다 . ▼ 함수명 그대로 별칭으로 쓰는 예시 */ defineExpose({showAlert}) // defineExpose({'showAlert', showAlert})이랑 같은 내용인데 축약버전 </script>