Vue3组合式API:getCurrentInstance

官方文档现已找不到此api,可寻找其他替代方案

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

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

在Vue3中,getCurrentInstance()可以用来获取当前组件实例 

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对象。 

  • 10
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值