Home> Web Front-end> Vue.js> body text

How to use getCurrentInstance in Vue3 with ts

王林
Release: 2023-05-15 22:37:04
forward
2161 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:

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: 'error', text: '登录失败' });
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('请xxx!')
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