Vue3父组件调用子组件的方法

在 Vue 3 组合式 API 中,如果要在父组件中调用子组件的方法,可以按照以下步骤操作:

  1. 子组件定义方法:在子组件内部定义一个方法,并暴露给外部使用。
  2. 父组件引用子组件实例:父组件通过 ref 创建一个引用,并将这个引用绑定到子组件上。
  3. 父组件调用子组件的方法:使用创建的引用调用子组件的方法。

下面是一个具体的示例:

//子组件
<template>
  <div>
    <button @click="showModal">Show Modal</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 定义一个方法
function showModal() {
  console.log('Modal shown');
}

defineExpose({ showModal });
</script>
//父组件 (ParentComponent.vue)

<template>
  <div>
    <child-component ref="childRef" />
    <button @click="callChildMethod">Call Child Method</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const childRef = ref(null);

function callChildMethod() {
  if (childRef.value && childRef.value.showModal) {
    childRef.value.showModal();
  }
}
</script>

在这个例子中:

  • 子组件 (ChildComponent.vue) 定义了一个 showModal 方法并通过 defineExpose 暴露出去。
  • 父组件 (ParentComponent.vue) 通过 ref 创建了对子组件的引用 childRef,并在按钮点击事件中调用了子组件的方法。

这样设置后,当点击父组件中的按钮时,就会调用子组件的 showModal 方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值