vue3 调用子组件的方法

78 篇文章 2 订阅
40 篇文章 1 订阅

child.vue

<template>

</template>
<script setup>
const DoSomeThing = () => {
    alert('点击事件');
}

// 输出组件的方法,让外部组件可以调用
defineExpose({
    DoSomeThing,
})


</script>
<style lang="less" scoped>

</style>

parent.vue

<template>
    <childVue ref="child" />

    <a-button type="primary" @click="ChildEvent">调用子组件的方法</a-button>
</template>
<script setup>
// setup 模式下,直接引用 Vue 文件,则相当于在组件中,注册了子组件
import { onMounted, ref } from 'vue';
import childVue from './child.vue';

// 创建于子组件同名的 变量名,则相当于获取了这个组件的实例
// 注意 : setup 模式下,不要让 子组件上的 ref 值 与创建的变量值重名😓
const child = ref();

// 子组件实例只有 在组件被挂载之后才能被调用
onMounted(() => {
    console.log(child.value);
})

const ChildEvent = () => {
    child.value.DoSomeThing();
}



</script>

<style lang="less" scoped>

</style>
  • 12
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值