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:
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: '登录失败' });
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!')
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!