Vue3 父子组件相互调用

369 阅读1分钟

父组件调用子组件,接收子组件参数

  • 父组件
<template>
    <Button @click="getSon">触发子组件方法</Button>
    <!-- 定义 ref -->
    <Son ref="son" @doSth2="sayHello" />
</template>
<script setup>
// 定义 ref 同名变量
const son = ref(null);

const getSon = () => {
    // 调用子组件
    son.value.doSon("这是父组件调用子组件");
    // 打印子组件参数
    console.log("父组件接收到了子组件参数:" + son.value.sonName);
}
</script>
  • 子组件
<template>
</template>

<script setup>
// 子组件方法
const doSon = (str) => {
    console.log("子组件的 doSon 方法执行了:" + str);
}

// 定义子组件参数
const sonName = ref("我是子组件参数Name")

// 暴露方法和参数
defineExpose({ doSth, sonName })
</script>

子组件调用父组件方法,接收父组件参数

  • 父组件
<template>
    <!-- 使用 @doSon 接收方法 -->
    <Son ref="son" @doSon="fatherMethod" />
</template>

<script setup>
import { provide,ref } from 'vue';

const fatherMethod = () => {
  console.log("子组件调用了父组件方法");
}

// 父函数传参给子孙的函数
provide('fatherData', "我是父组件传过来的值");
</script>
  • 子组件
<template>
</template>
<script setup>
import { inject,ref } from 'vue';

// 注册事件,让其可以被父组件调用
const emit = defineEmits(["doSon"]);
const doSon = () => {
    // 触发事件,父组件调用方法
    emit('doSon');
}

// 子接收父传过来的参数
const fatherData = inject('fatherData')
console.log("子组件接收了父组件传过来的参数:" + testData1);
</script>