报错:类型“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 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖4 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神4 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛6 小时前
Nginx日志切分
服务器·前端·nginx
北原_春希6 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
尽意啊6 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜6 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive6 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…6 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.6 小时前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts