报错:类型“ComponentInternalInstance | null”上不存在属性“proxy”。ts(2339)

问题

在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()
相关推荐
纯爱掌门人3 小时前
鸿蒙端云一体化云存储实战:手把手教你玩转文件上传下载
前端·harmonyos
非凡ghost3 小时前
图吧工具箱-电脑硬件圈的“瑞士军刀”
前端·javascript·后端
非凡ghost3 小时前
Xrecode3(多功能音频转换工具)
前端·javascript·后端
橙某人3 小时前
飞书多维表格插件:进一步封装,提升开发效率!🚀
前端·javascript
他们叫我秃子3 小时前
从 0 到 1,我用小程序 + 云开发打造了一个“记忆瓶子”,记录那些重要的日子!
前端·微信小程序·小程序·云开发
非凡ghost3 小时前
Subtitle Edit(字幕编辑软件) 中文绿色版
前端·javascript·后端
扎瓦斯柯瑞迫3 小时前
cursor: 10分钟魔改环境、优雅获取Token
前端·javascript·后端
王六岁3 小时前
🐍 前端开发 0 基础学 Python 入门指南:条件语句篇
前端·python
San303 小时前
CSS3 星球大战:用前端技术打造震撼的3D动画效果
前端·css·html
用户12039112947263 小时前
从零构建一个HTML5敲击乐Web应用:前端开发最佳实践指南
前端