iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >Vue3组合式API之getCurrentInstance详解
  • 515
分享到

Vue3组合式API之getCurrentInstance详解

2024-04-02 19:04:59 515人浏览 泡泡鱼
摘要

Vue2中,可以通过this来获取当前组件实例;  vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefine

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

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

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

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()  

使用proxy线上也不会出现问题

总结 

到此这篇关于Vue3组合式api之getCurrentInstance详解的文章就介绍到这了,更多相关Vue3组合式API getCurrentInstance内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Vue3组合式API之getCurrentInstance详解

本文链接: https://www.lsjlt.com/news/168391.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作