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>