报错:类型“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()
相关推荐
程序员小寒8 分钟前
前端高频面试题之CSS篇(一)
前端·css·面试·css3
颜酱24 分钟前
Monorepo 架构以及工具选型、搭建
前端·javascript·node.js
oden28 分钟前
ChatGPT不推荐你?7个GEO技巧让AI主动引用你的内容
前端
李游Leo1 小时前
前端安全攻防指南:XSS / CSRF / 点击劫持与常见防护实践(含真实案例拆解)
前端·安全·xss
我命由我123452 小时前
微信开发者工具 - 模拟器分离窗口与关闭分离窗口
前端·javascript·学习·微信小程序·前端框架·html·js
E***q5392 小时前
Vue增强现实开发
前端·vue.js·ar
S***42802 小时前
JavaScript在Web中的Angular
前端·javascript·angular.js
黑幕困兽2 小时前
ehcarts 实现 饼图扇区间隙+透明外描边
前端·echarts
San302 小时前
深入理解 JavaScript 词法作用域链:从代码到底层实现机制
前端·javascript·ecmascript 6
七淮2 小时前
Next.js SEO 优化完整方案
前端·next.js