>  기사  >  웹 프론트엔드  >  ts와 함께 Vue3에서 getCurrentInstance를 사용하는 방법

ts와 함께 Vue3에서 getCurrentInstance를 사용하는 방법

王林
王林앞으로
2023-05-15 22:37:042169검색

getCurrentInstance는 ts와 함께 사용됩니다

vue3 프로젝트에서는 ts 없이 사용해도 문제 없습니다

const { proxy } = getCurrentInstance()

ts에서 사용하면 오류가 발생합니다: Error:...Type "ComponentInternalInstance | null"

우리는 일반적으로 프로젝트에서 이 작업을 수행합니다. 많은 getCurrentInstance() 메소드가 사용되며 직접 캡슐화합니다.

useCurrentInstance.ts 파일 생성:

import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export default function useCurrentInstance() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const proxy = appContext.config.globalProperties
    return {
        proxy
    }
}

컴포넌트 내에서 사용:

<script lang="ts">
import { defineComponent } from "vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
export default defineComponent({
  setup() {
    const { proxy } = useCurrentInstance();
    console.log(proxy);
  },
});
</script>

vue3+ts는 getCurrentInstance를 사용하여 보고합니다. error

vue3에는 이 기능이 없습니다. + 다양한 API 메소드

vue3 이와 유사한 인스턴스를 생성하는 메소드를 제공합니다.

const instance = getCurrentInstance() 

const a1= getCurrentInstance();
a1.$toast({type: &#39;error&#39;, text: &#39;登录失败&#39; });

이것은 로컬 디버깅에만 적합합니다. 온라인으로 실행할 때 오류가 보고됩니다. 오류 세부 정보는 다음과 같습니다.

"proxy" 속성은 "ComponentInternalInstance | null" 유형에 존재하지 않습니다. ts(2339)

이 오류는 아래에 보고됩니다

`any` 값에 대한 안전하지 않은 구성원 액세스 .$axios eslint@typescript-eslint/no-unsafe-member-access

`any의 안전하지 않은 호출. ` 입력된 값입니다. eslint@typescript-eslint/no-unsafe-call

이유: getCurrentInstance()의 반환 유형이 null이므로 여기에 어설션을 추가하면 됩니다.

Null 결과를 필터링하려면 프록시 뒤에 ?를 추가하세요. 즉,

const instance = getCurrentInstance()?.proxy  
 instance ?.$toast(&#39;请xxx!&#39;)

위 내용은 ts와 함께 Vue3에서 getCurrentInstance를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제