Vue3父组件调用子组件方法

父组件:通过ref获取子组件实例
子组件:通过defineExpose暴露方法

<template>
  <div style="text-align:center">
    <button @click="callChildMethod">点击获取子组件数据</button>
    <div>
      获取到子组件的数据如下:
      <div> {{childData}} </div>
    </div>
    <ChildComponent ref="ChildComponentRef"/>
  </div>
</template>

<script setup>
  import { ref } from "vue";
  import ChildComponent from "@/components/childComponent.vue";
  
  const ChildComponentRef = ref(null); // 获取子组件实例(需要跟ref处同名)
  let childData = ref();
  const callChildMethod = () =>{
    if (ChildComponentRef.value) {
      childData.value = ChildComponentRef.value.userName +'在'+ ChildComponentRef.value.doSomething() 
    }
  }
</script>

defineExpose 是 Vue 3.2 引入的一个新 API,它是 <script setup> 的配套 API 之一。在 <script setup> 中,所有定义的变量和函数默认是私有的,不能从组件外部访问。
defineExpose 的引入是为了提供一种清晰的方式来控制组件的公共接口,避免所有的内部状态都被外部访问,从而增强组件的封装性。
如果你想让外部组件访问到 <script setup> 内定义的属性或方法,你需要使用 defineExpose 显式地暴露它们。

<template>
  <!-- <p>子组件</p> -->
</template>

<script setup>
  import { ref, defineExpose } from "vue";
  const userName = ref("张三");
  function doSomething() {
    return "写代码"
  };

  // 暴露方法
  defineExpose({
    doSomething,
    userName,
  });
</script>

在上面的代码中,doSomething 和 userName是在 <script setup> 中定义的,通过 defineExpose 将它们暴露给父组件。这样,父组件就可以通过模板引用(ref)或者 setup() 函数的 context.expose 属性来访问这些暴露的属性和方法。
效果:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容