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

相关推荐
zwjapple18 分钟前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20202 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
aiprtem3 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊3 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术3 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
幽络源小助理3 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
GISer_Jing3 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止4 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall4 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴4 小时前
简单入门Python装饰器
前端·python