getCurrentInstance在vue3中遇到的问题

在项目升级中碰到的问题

父组件A通过$refs调用子组件B的方法时候出现的bug

两个组件都是script setup写法

image.png

Uncaught TypeError: Cannot read properties of null (reading 'proxy')

A在通过$refs调用B的openPicker的方法,
B组件中的写法

    const openPicker = () => {
        const { proxy } = getCurrentInstance();
        proxy.$refs.picker.show = true;
    };

    defineExpose({ openPicker });

openPicker是通过defineExpose暴露出去的
ps:setup里面定义的方法和变量都是不会暴露出去的,想通过组件引用来使用就必须要用defineExpose

解决方法
const { proxy } = getCurrentInstance();不能写在openPicker里面,把它移出来就行了

    const { proxy } = getCurrentInstance();
    const openPicker = () => {
        proxy.$refs.picker.show = true;
    };

    defineExpose({ openPicker });
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容