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

相关推荐
岁月宁静11 分钟前
深度定制:在 Vue 3.5 应用中集成流式 AI 写作助手的实践
前端·vue.js·人工智能
心易行者1 小时前
10天!前端用coze,后端用Trae IDE+Claude Code从0开始构建到平台上线
前端
saadiya~1 小时前
ECharts 实时数据平滑更新实践(含 WebSocket 模拟)
前端·javascript·echarts
fruge1 小时前
前端三驾马车(HTML/CSS/JS)核心概念深度解析
前端·css·html
百锦再1 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net
烛阴2 小时前
Lua 模块的完整入门指南
前端·lua
Sheldon一蓑烟雨任平生2 小时前
Vue3 表单输入绑定
vue.js·vue3·v-model·vue3 表单输入绑定·表单输入绑定·input和change区别·vue3 双向数据绑定
浪里行舟2 小时前
国产OCR双雄对决?PaddleOCR-VL与DeepSeek-OCR全面解析
前端·后端
znhy@1233 小时前
CSS易忘属性
前端·css
瓜瓜怪兽亚3 小时前
前端基础知识---Ajax
前端·javascript·ajax