VUE3.2.25父子组件函数调用

1、子组件调用父组件函数

子组件

<template>
    <p>这是子组件</p>
    <button @click="callParentFunc">调用父组件函数</button>
</template>
<script setup>
const emit = defineEmits(["parentFunc"]);
function callParentFunc() {
    emit('parentFunc', 'arg1', 'arg2');
}
</script>

父组件

<template>
    <p>这是父组件</p>
    <childcomp @parentFunc="selfFunc"/>
</template>
<script setup>
import childcomp from './childcomp.vue';
function selfFunc(arg1, arg2) {
    console.log(arg1);
    console.log(arg2);
}
</script>

2、父组件调用子组件函数

子组件

<template>
    <p>这是子组件</p>
</template>
<script setup>
function subCompFunc() {
    console.log("subCompFunc is called!");
}
defineExpose({ subCompFunc });
</script>

父组件

<template>
    <p>这是父组件</p>
    <button @click="selfFunc">调用子组件函数</button>
    <childcomp ref="childComp"/>
</template>
<script setup>
import { ref } from "vue";
import childcomp from './childcomp.vue';

const childComp = ref();
function selfFunc() {
    childComp.value.subCompFunc();
}
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容