Home  >  Article  >  Web Front-end  >  How to use getCurrentInstance in Vue3 with ts

How to use getCurrentInstance in Vue3 with ts

王林
王林forward
2023-05-15 22:37:042169browse

getCurrentInstance is used in combination with ts

In the vue3 project, it is okay to use it without ts

const { proxy } = getCurrentInstance()

If used in ts, an error will be reported: Error:... Type "ComponentInternalInstance | null”

We generally use many getCurrentInstance() methods in our projects, and encapsulate them directly

Create useCurrentInstance.ts file:

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

Use within the component:

<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 reports an error when using getCurrentInstance

There is no this in vue3 Various api methods

Vue3 provides methods to create instances similar to this.

const instance = getCurrentInstance() 

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

This is only suitable for local debugging. An error will be reported when running online. The error details are:

The attribute "proxy" does not exist on the type "ComponentInternalInstance | null". ts(2339)

Then this error will be reported below

Unsafe member access .$axios on an `any` value. eslint@typescript-eslint/no-unsafe-member- access

Unsafe call of an `any` typed value. eslint@typescript-eslint/no-unsafe-call

Reason:

## The return type of #getCurrentInstance() is null, so just add an assertion here.

Add ? after proxy to filter null results, that is:

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

The above is the detailed content of How to use getCurrentInstance in Vue3 with ts. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete