vue3+ts 组合式api中(setup)如何使用getCurrentInstance,以及用它替代this

vue3的setup中没有this时需要使用getCurrentInstance()来获取。getCurrentInstance()可以用来获取当前组件实例

let { proxy } = getCurrentInstance();

getCurrentInstance是一个function方法,getCurrentInstance()是一个对象,proxy也是一个对象。proxy是getCurrentInstance()对象中的一个属性,通过对象的解构赋值方式拿到proxy。

getCurrentInstance只能在setup或生命周期钩子中使用。

开发中只适用于调试! 不要用于线上环境,否则会有问题!另外官方不推荐用它来作为组合式api中获取this的替代方案,原因我也不清楚

javascript 复制代码
import { getCurrentInstance } from 'vue'
const { proxy} = getCurrentInstance()

这种只适合本地调试,运行到线上就会报错,为ts的类型错误,类型"ComponentInternalInstance | null"上不存在属性"proxy"的错误

此时我用这中方式就能解决

javascript 复制代码
import type { ComponentInternalInstance } from 'vue'
const { proxy } = getCurrentInstance() as ComponentInternalInstance

如果又更多的错误问题 可以参考这篇文章

https://blog.csdn.net/weixin_47239456/article/details/132281059?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-132281059-blog-127795552.235%5Ev38%5Epc_relevant_anti_vip&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-132281059-blog-127795552.235%5Ev38%5Epc_relevant_anti_vip&utm_relevant_index=2

相关推荐
木易士心1 分钟前
从 MVP 到千万级并发:AI 在前后端开发中的差异化落地指南
前端·后端
葡萄城技术团队4 分钟前
字体与打印:前端开发最常见的三个“为什么”
前端
王夏奇6 分钟前
python中的深浅拷贝和上下文管理器
java·服务器·前端
siger11 分钟前
徒手开荒-我用纯Nodejs+pnpm+monorepo改造了一个多vue2的iframe"微前端"项目
前端·node.js·前端工程化
lichenyang45311 分钟前
海克斯大乱斗攻略网站 —— 从零开发到云服务器部署全记录
前端
你的代码僚机14 分钟前
《别再被 SSO 骗了!前端单点登录原理+避坑指南》
前端
不懂代码的切图仔30 分钟前
移动端h5实现横屏在线签名
前端·微信小程序
少卿33 分钟前
OpenClaw 的 summarize 技能——开发者的智能摘要利器
前端·后端·程序员
仰望.33 分钟前
vue vxe-table 数据分组与排序的实现方式
vue.js·vxe-table
麦秋35 分钟前
前端静态页面自动生成(Figma MCP + VS code + Github copilot)
前端·vue.js