vue3 调用子组件的方法

时间:2025-04-08 08:16:43
<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 './'; // 创建于子组件同名的 变量名,则相当于获取了这个组件的实例 // 注意 : setup 模式下,不要让 子组件上的 ref 值 与创建的变量值重名???? const child = ref(); // 子组件实例只有 在组件被挂载之后才能被调用 onMounted(() => { console.log(child.value); }) const ChildEvent = () => { child.value.DoSomeThing(); } </script> <style lang="less" scoped> </style>