1.3.3. vue3 父调用子 a, 子 a 调用父,子调用父子 b
1.3.3.1. 父组件(Father.vue)
<template> <ChildA ref="childA" @go="fatherMethod" :childB="childB" /> <ChildB ref="childB" /> </template> <script setup> import { ref } from 'vue' import ChildA from './ChildA.vue' import ChildB from './ChildB.vue' // 拿到子组件 ref const childA = ref(null) const childB = ref(null) // 父方法(子A要调用) function fatherMethod(msg) { console.log('父方法被调用:', msg) } // 父调用子A const callChildA = () => { childA.value.aMethod() } // 父调用子B const callChildB = () => { childB.value.bMethod() } </script>
1.3.3.2. 子 A 组件(ChildA.vue)
<template> <button @click="callFather">子A调用父方法</button> <button @click="callChildB">子A调用子B方法</button> </template> <script setup> import { defineEmits, defineProps } from 'vue' // 1. 子调用父 → emit(最标准!) const emit = defineEmits(['go']) const callFather = () => { emit('go', '我是子A,调用父方法') } // 2. 子A调用子B → 父把 childB ref 传给子A const props = defineProps({ childB: { type: Object, default: null } }) const callChildB = () => { if (props.childB) { props.childB.bMethod() } } </script>
1.3.3.3. 子 B 组件(ChildB.vue)
<template></template> <script setup> import { defineExpose } from 'vue' // 子B方法(父/子A要调用) const bMethod = () => { console.log('子B方法被调用') } // 必须暴露!否则外面拿不到 defineExpose({ bMethod }) </script>