Home > Web Front-end > Vue.js > How to use getCurrentInstance in Vue3 with ts

How to use getCurrentInstance in Vue3 with ts

王林
Release: 2023-05-15 22:37:04
forward
2322 people have browsed it

getCurrentInstance is used in combination with ts

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

const { proxy } = getCurrentInstance()
Copy after login

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
    }
}
Copy after login

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>
Copy after login

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; });
Copy after login

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;)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template