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

相关推荐
悟忧17 小时前
规避ProseMirror React渲染差异带来的BUG
前端
小皮虾17 小时前
小程序云开发有类似 uniCloud 云对象的方案吗?有的兄弟,有的!
前端·javascript·小程序·云开发
QuantumLeap丶17 小时前
《uni-app跨平台开发完全指南》- 05 - 基础组件使用
vue.js·微信小程序·uni-app
Android疑难杂症17 小时前
鸿蒙Notification Kit通知服务开发快速指南
android·前端·harmonyos
T___T17 小时前
全方位解释 JavaScript 执行机制(从底层到实战)
前端·面试
阳懿17 小时前
meta-llama-3-8B下载失败解决。
前端·javascript·html
Qinana17 小时前
🌊 深入理解 CSS:从选择器到层叠的艺术
前端·css·程序员
IT_陈寒17 小时前
Python 3.12新特性实测:10个让你的代码提速30%的隐藏技巧 🚀
前端·人工智能·后端
史林枫17 小时前
JavaScript 中call和apply的详细讲解 —— 连10岁的小朋友都能看懂!
javascript·apply·call
闲人编程17 小时前
从零开发一个简单的Web爬虫(使用Requests和BeautifulSoup)
前端·爬虫·beautifulsoup·bs4·web·request·codecapsule