明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
随笔 - 1276, 文章 - 0, 评论 - 214, 阅读 - 320万
  博客园  :: 首页  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Vue3组合式API之getCurrentInstance详解

Posted on   且行且思  阅读(6453)  评论(0编辑  收藏  举报

Vue2中,可以通过this来获取当前组件实例; 

Vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefined。

在Vue3中,getCurrentInstance()可以用来获取当前组件实例  vue3官方文档解释

1
let { proxy } = getCurrentInstance();

 

在setup中分别打印下面3个值,结果如下:

  console.log(getCurrentInstance,typeof(getCurrentInstance));
  console.log(getCurrentInstance(),typeof(getCurrentInstance()));
  console.log(proxy,typeof(proxy));

 

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

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

1.在onMunted生命周期中打印getCurrentInstance

2.定义一个test方法,通过click事件触发方法

onMounted(() => {
  console.log(getCurrentInstance(), typeof getCurrentInstance());
});
function test() {
  console.log(getCurrentInstance(), typeof getCurrentInstance());
}

 

看到在function中是无法获取该实例的。

let { ctx } = getCurrentInstance();
console.log(ctx, typeof ctx);
let { proxy } = getCurrentInstance();
console.log(proxy, typeof proxy);

 

ctx和proxy都是getCurrentInstance()对象中的属性,通过解构赋值的方式拿到。可以看到,2者有所区别。ctx是普通对象,proxy是Proxy对象。

补充:Vue3中关于getCurrentInstance的大坑

开发中只适用于调试! 不要用于线上环境,否则会有问题!

解决方案:

方案1.

const instance = getCurrentInstance()
console.log(instance.appContext.config.globalProperties)

 

获取挂载到全局中的方法

方案2.

const { proxy } = getCurrentInstance()  

 

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2014-02-21 IIS:日志代码分析
2012-02-21 C# DateTime ToString
点击右上角即可分享
微信分享提示