问题
在vue3+ts项目中,使用const { proxy } = getCurrentInstance()
报错:...类型"ComponentInternalInstance | null"

解决
既然会用到很多次getCurrentInstance()方法,索性直接封装一下
创建utils/useCurrentInstance.ts:
ts
import { getCurrentInstance } from 'vue'
import type { ComponentInternalInstance } from 'vue'
export default function useCurrentInstance() {
const instance = getCurrentInstance() as ComponentInternalInstance | null
// 确保实例存在
if (!instance) {
throw new Error('useCurrentInstance must be used within a component setup')
}
const proxy = instance.appContext.config.globalProperties
return {
proxy
}
}
使用时:
js
import useCurrentInstance from '@/utils/useCurrentInstance'
const { proxy } = useCurrentInstance()