我们可以通过 getCurrentInstance这个函数来返回当前组件的实例对象,也就是当前vue这个实例对象,下面这篇文章主要给大家介绍了关于Vue3组合式API之getCurrentInstance的相关资料,需要的朋友可以参考下

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, typeo(proxy));

img

可以看到,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());
}

img

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

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

img

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

补充:Vue3中关于getCurrentInstance的大坑

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

解决方案:

方案1.

// main.ts
// 注册全军变量
app.config.globalProperties.$message = 'Hello lxl'
const instance = getCurrentInstance()
console.log(instance.appContext.config.globalProperties.$message)

获取挂载到全局中的方法

方案2.

const { proxy } = getCurrentInstance() 
console.log(proxy.$message)

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

备注:

  • getCurrentInstance: 获取挂载在全局的属性
  • ComponentPublicInstance: 获取上下文
  • ComponentCustomProperties: 组件公共实例