vue3父组件 调用子组件 方法

父组件:通过ref获取子组件实例

<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 显式地暴露它们。
 
子组件:通过defineExpose暴露方法
<template>
  <!-- <p>子组件</p> -->
</template>

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

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

 

posted @ 2024-07-04 15:33  林财钦  阅读(6)  评论(0编辑  收藏  举报