要实现 A 方法调用后,B 子组件的方法也被调用并获取 A 传递的参数,可以使用事件总线的方式来解决。下面是具体的实现步骤:
- 新建一个 EventBus.js 文件,用于创建一个全局的事件总线:
import mitt from 'mitt'; const eventBus = mitt(); export default eventBus;
- 在 A 组件中,触发事件并传递参数:
<template> <button @click="callA">Call A</button> </template> <script> import { ref } from 'vue'; import eventBus from './EventBus'; export default { setup() { const callA = () => { const data = 'Hello from A'; eventBus.emit('a-called', data); }; return { callA }; } } </script>
在上面的代码中,我们在点击按钮时,通过
eventBus.emit
方法触发名为 'a-called' 的事件,并传递了参数 'Hello from A'。 - 在 B 组件中监听 'a-called' 事件,并调用对应的方法获取传递的参数:
<script> import { ref, onMounted } from 'vue'; import eventBus from './EventBus'; export default { setup() { const bData = ref(''); const handleACalled = (data) => { // 在这里处理 A 调用后的逻辑,获取传递的参数 bData.value = data; }; onMounted(() => { eventBus.on('a-called', handleACalled); }); return { bData }; } } </script>
在上面的代码中,我们使用
eventBus.on
方法来监听 'a-called' 事件,并在事件触发时执行handleACalled
方法。在handleACalled
方法中,我们可以获取到 A 组件传递的参数,并进行后续处理。这样,当 A 组件调用了
callA
方法后,B 组件中的handleACalled
方法会被调用,并获取到 A 传递的参数。