当前位置: 首页 > news >正文

vue3 组合式API获取子组件的属性和方法

  1. 在vue2中,获取子组件实例的方法或者属性时,父组件直接通过ref即可直接获取子组件的属性和方法,如下:

    // father.vue
    <child ref="instanceRef" />
    this.$ref['instanceRef'].testVal
    this.$ref['instanceRef'].testFunc()
    // child.vue
    data () {return {testVal: '来自子组件的属性'}
    },
    methods: {testFunc() {return '来自子组件的方法'}
    }
    
  2. 在vue3 组合式API中,在子组件使用defineExpose指定需要暴露的属性和方法,父组件才可以通过ref获取到子组件的属性和方法,如下:

    // father.vue
    <script setup lang="ts">
    import ChildInstance from "@/views/component/father-instance/child-instance.vue";
    import { ref } from "vue";const instanceRef = ref(null);
    const getChildInstance = () => {const childInstance = instanceRef.value; // 通过ref获取子组件实例console.log(childInstance.childValue);console.log(childInstance.childFunc());
    };
    </script><template><ChildInstance ref="instanceRef" /><el-button @click="getChildInstance">获取子组件属性和方法</el-button>
    </template><style scoped lang="scss"></style>
    // child.vue
    <script setup lang="ts">
    import { ref, defineExpose } from "vue";const childValue = ref("来自子组件的属性");
    const childFunc = () => {return "来自子组件的方法";
    };
    // 使用defineExpose指定需要暴露的属性和方法
    defineExpose({childValue,childFunc
    });
    </script><template><div>来自子组件</div>
    </template><style scoped lang="scss"></style>
http://www.lryc.cn/news/290518.html

相关文章:

  • [数据结构+算法] 给一棵树和一个sum,判断是否存在从root到叶子结点的path之和等于sum?
  • 非阿里云注册域名如何在云解析DNS设置解析?
  • 微服务-微服务Alibaba-Nacos注册中心实现
  • 多符号表达式的共同子表达式提取教程
  • Java 反射获取属性名、属性类型、属性值、判断属性类型
  • Docker私有仓库搭建
  • C语言第十三弹---VS使用调试技巧
  • AST反混淆实战-jsjiamiv7最高配置
  • colorThief+vite+react使用方法
  • Hive(15)中使用sum() over()实现累积求和和滑动求和
  • 2024年Java搭建面试题
  • 二维数组的学习
  • Java集合(List集合)
  • 7、Json文件的操作总结【robot framework】
  • python 循环解压 解压多重压缩包
  • 基于C#制作一个连连看小游戏
  • Android-System 根据包名查找已安装应用apk方法
  • 洛谷-P4124题-手机号码-Java
  • 仅使用 Python 创建的 Web 应用程序(前端版本)第08章_商品详细
  • Stable Diffusion 长视频真人动画风格互转
  • 精要图示:园区金融数字化服务蓝图,以园区为支点推动信贷业务增长
  • 2024 中国(南京)国际口腔设备器械博览会
  • 【MyBatis】快速入门MyBatis(保姆式教学),你值得一看
  • git pull代码时候报错:error: cannot open .git/FETCH_HEAD: Permission denied
  • shell - 正则表达式和grep命令和sed命令
  • datawhale 大模型学习 第十二章-大模型环境影响
  • Qt WebEngine模块使用(开发环境安装和程序开发)
  • 网络体系结构 和网络原理之UDP和TCP
  • 将Android APP安装到sm8550 HDK的NVMe SSD
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息