[Vue3] getCurrentInstance

ChanSol Jeong·2023년 7월 6일
0

Vue

목록 보기
6/6
post-thumbnail

<script setup>에서는 component instancethis가 없다.

Option APIthis를 어쩔수없이 사용하려면 getCurrentInstance를 사용하는 방법이 있다.

<script setup>
import { getCurrentInstance } from "vue";

// 현재 실행중인 component의 instance
// 내부실행 API이므로 사용을 권장하지않지만 <script setup>에서는 instnace내부의 this에 접근할수없어서
// Option API의 this의 역할을 수행하려면 사용해야한다.
const app = getCurrentInstance();

//실행중인 component instance의 함수이름을 매개변수로 받아 실행하는 방법
//Option API에서는 this[functionName]()으로 사용가능
const executeFunction = (functionName) => {
  if (functionName && app.setupState[functionName]) {
      app.setupState[functionName]();
  }
};

getCurrentInstance는 과거에 공식문서에 올라와있는 API였으나 현재는 deprecated 상태이다.

외부에 노출되지 않는 내부실행 API로써 무분별한 사용은 소스에 어떠한 영향을 줄지 알수없으므로 조심해서 사용하자.

참고하면 좋은 issue : https://github.com/vuejs/vue/issues/12596#issuecomment-1173269807

profile
Compostion API 맛있다!

0개의 댓글