报错:类型“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()
相关推荐
慢半拍iii1 小时前
JAVA Web —— A / 网页开发基础
前端
gnip1 小时前
pnpm 的 monorepo架构多包管理
前端·javascript
新手村领路人2 小时前
Firefox自定义备忘
前端·firefox
乖女子@@@3 小时前
css3新增-网格Grid布局
前端·css·css3
伐尘3 小时前
【CE】图形化CE游戏教程通关手册
前端·chrome·游戏·逆向
不想吃饭e3 小时前
在uniapp/vue项目中全局挂载component
前端·vue.js·uni-app
非凡ghost4 小时前
AOMEI Partition Assistant磁盘分区工具:磁盘管理的得力助手
linux·运维·前端·数据库·学习·生活·软件需求
UrbanJazzerati4 小时前
前端入门:margin居中、border、box-radius、transform、box-shadow、mouse事件、preventDefault()
前端·面试
蝎子莱莱爱打怪4 小时前
🚀🚀🚀嗨,一起来开发 开源IM系统呀!
前端·后端·github
Enddme4 小时前
《前端笔试必备:JavaScript ACM输入输出模板》
前端·javascript·面试