父组件

<template>
    <div class="parent">
        <button @click="getChild">触发子组件方法</button>
        <!-- 1. 定义ref -->
        <child ref="childRef"></child>
    </div>
</template>
<script lang="ts" stup>
    import { defineComponent, ref } from "vue";
    import child from "@/components/child.vue";
 
    // 2. 定义与ref同名变量
    const childRef = ref<any>();
    const getChild = () => {
        childRef.value.childFun();
    }
</script>

子组件 scrip setup 写法

<template>
    <div class="child">
    </div>
</template>
<script lang="ts" stup>

 const childFun = () => {
     console.log('已触发组件方法');
 }

 //关键点 把 方法暴露给父组件
 defineExpose({open})

</script>

子组件 defineComponent 写法

<template>
    <div class="child">
    </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
 
 
export default defineComponent({
    setup() {
        // 子组件的方法
        const childFun = () => {
            console.log('已触发组件方法');
        }
        return {
            childFun
        };
    },
   
});
</script>

Logo

前往低代码交流专区

更多推荐