Property ‘proxy‘ does not exist on type ‘ComponentInternalInstance | null‘.ts

问题

Vue 3 使用 getCurrentInstance 获取当前正在执行的组件实例 TypeScript 报错。

typescript 复制代码
const { proxy } = getCurrentInstance();  

报错信息:

typescript 复制代码
Property 'proxy' does not exist on type 'ComponentInternalInstance | null'.ts

解决方案

在Vue 3的Composition API中,getCurrentInstance()返回的类型是ComponentInternalInstance | null。因此,当你使用const { proxy } = getCurrentInstance();时,TypeScript会报错,因为proxy属性在类型定义中并不存在。

为了解决这个问题,你可以使用类型断言(Type Assertion)来告诉TypeScript你确信返回的实例是非空的。在这种情况下,你可以使用非空断言!:

typescript 复制代码
const { proxy } = getCurrentInstance()!;

请注意,使用非空断言表示你确信getCurrentInstance()永远不会返回null。如果你不能确保这一点,最好在代码中进行适当的空值检查。例如:

typescript 复制代码
const instance = getCurrentInstance();

if (instance) {
  const { proxy } = instance;
  // 现在你可以安全地使用 proxy
} else {
  console.error("无法获取组件实例");
}
相关推荐
zl0_00_05 分钟前
xss-lab
前端·网络·xss
爱上你家菜包11 分钟前
Electron一小时快速上手
前端·javascript·electron
陈琦鹏12 分钟前
Vue3+Vite开发Electron桌面端问题记录
前端·javascript·electron
什么什么什么?34 分钟前
el-input实现金额输入
javascript·vue.js·elementui
工业互联网专业2 小时前
基于springboot+vue的融合多源高校画像数据与协同过滤算法的高考择校推荐系统
java·vue.js·spring boot·毕业设计·源码·课程设计·高考择校推荐系统
狼性书生2 小时前
uniapp vue3实现的一款数字动画调节器件,支持长按、单点操作,提供丝滑的增减动画效果
前端·vue.js·微信小程序·小程序·uni-app
Jelena157795857922 小时前
爬虫获取微店商品快递费 item_feeAPI 接口的完整指南
开发语言·前端·爬虫
qq_12498707532 小时前
Java+Vue+uniapp微信小程序校园自助打印系统(程序+论文+讲解+安装+调试+售后)
vue.js·微信小程序·uni-app·毕业设计
总是学不会.2 小时前
从“记住我”到 Web 认证:Cookie、JWT 和 Session 的故事
java·前端·后端·开发
xinran_Yi3 小时前
XSS-labs靶场通关
前端·xss