报错:类型“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()
相关推荐
陈随易4 小时前
bm2,Node.js 与 Bun 项目部署新选择
前端·后端·程序员
福兮说5 小时前
canvas 旋转图片的六个坑:四角被裁、Math.ceil 多出 1px 黑边、JPG 角发黑、翻转方向反了
前端·javascript·图像处理·canvas
传人once7 小时前
多图片上传预览功能如何写
前端·css·html·jquery·html5
Eric.467 小时前
Wan‑Animate+MiniMax-H3 本地部署 AI 漫剧流水线:8G 显存动作迁移与动态分镜工程实战
前端·人工智能·comfyui·ai漫剧
库拉镜像AI牛牛9 小时前
短剧内容自动化生产:知漫剧工作室落地教程
大数据·服务器·前端·人工智能·语音识别
律宏阔9 小时前
Flutter 列表图片内存优化:CachedNetworkImage 与 ClipRRect 的取舍
前端·flutter
行者全栈架构师9 小时前
【鸿蒙心迹】相册文搜图工程化落地:HarmonyOS 7.0 端侧 AI 检索全链路实战与 5 个踩坑解法
前端
律宏阔9 小时前
Dart 3 Record:解决 Future.wait 异构返回值的类型问题
前端·flutter
Seraphina369 小时前
DVWA(XSS Reflected/Stored High,CSRF Low)
前端·xss·csrf
默_笙10 小时前
🍔 中间件不只是打日志:四个钩子、一次短路,和自带的工具
前端·javascript