报错:类型“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()
相关推荐
yanlele28 分钟前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang45333 分钟前
React移动端开发项目优化
前端·react.js·前端框架
你的人类朋友37 分钟前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
web_Hsir38 分钟前
vue3.2 前端动态分页算法
前端·算法
烛阴1 小时前
WebSocket实时通信入门到实践
前端·javascript
草巾冒小子1 小时前
vue3实战:.ts文件中的interface定义与抛出、其他文件的调用方式
前端·javascript·vue.js
DoraBigHead2 小时前
你写前端按钮,他们扛服务器压力:搞懂后端那些“黑话”!
前端·javascript·架构
Xiaouuuuua2 小时前
一个简单的脚本,让pdf开启夜间模式
java·前端·pdf
@Dream_Chaser3 小时前
uniapp ruoyi-app 中使用checkbox 无法选中问题
前端·javascript·uni-app
深耕AI3 小时前
【教程】在ubuntu安装Edge浏览器
前端·edge