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

相关推荐
MrDJun13 分钟前
分享一款免费实用的网页变动监控工具:PageWatch.tech
前端·javascript·vue.js
米码收割机14 分钟前
【web】邻里悦站—社区便民服务平【独一无二】(源码+说明文档)
前端
程序员爱钓鱼24 分钟前
Rust Option 详解:安全处理“可能存在,也可能不存在”的值
前端·后端·rust
程序员爱钓鱼25 分钟前
Go Modules 包管理详解:go.mod、go.sum 与依赖管理
前端·后端·go
qq_589666059 小时前
TypeScript 完整入门教程
前端·javascript·typescript
星栈独行10 小时前
翻完 Pi 源码:它和 Codex、Claude Code 有何不同
开发语言·javascript·人工智能·程序人生
落落Plus11 小时前
浏览器缓存机制详解
javascript·缓存·浏览器缓存
用户0595401744612 小时前
LLM对话记忆测试踩坑实录:手工回归30分钟,自动化后2分钟发现3个隐藏Bug
前端·css
Ashley的成长之路13 小时前
前端性能优化实战手册·第2篇:资源加载策略全解
前端·性能优化·资源加载·http/3·性能优化实战·资源加载优化