Vue3组合式API之getCurrentInstance详解(在行为验证码之滑动验证AJ-Captcha遇到在开发环境可以,测试环境报错)

首先大家知道我们可以通过 getCurrentInstance这个函数来获取当前组件的实例对象,也就是当前vue这个实例对象
在Vue2中,我们是可以通过this来获取当前组件实例;
但是在Vue3中,在setup中无法通过this获取组件实例的。所以在Vue3中,我们可以通过getCurrentInstance()来获取当前组件实例 。

	
let { proxy } = getCurrentInstance();
在setup中分别打印prox,getCurrentInstance,getCurrentInstance()3个值,
getCurrentInstance是一个function方法,getCurrentInstance()是一个对象,proxy也是一个对象。proxy是getCurrentInstance()对象中的一个属性,通过对象的解构赋值方式拿到proxy。 

注意:getCurrentInstance只能在setup或生命周期钩子中使用。

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线上也不会出现问题

由于本人在使用AJ-Captcha插件的过程中发现在开发环境调试正常,但是测试环境会报错,获取不到组件实例
原因在于使用了let { ctx } = getCurrentInstance();ctx获取
更换为const { proxy } = getCurrentInstance() ,恢复正常

你可能感兴趣的:(vue.js,javascript,前端)