vue3 子组件弹窗打开另一个子组件弹窗
时间: 2024-12-13 10:28:23 浏览: 45
在 Vue3 中,如果你想要在一个子组件(比如 ChildComponentA
)中触发并显示另一个独立的子组件(比如 ChildComponentB
的弹窗),你可以通过事件总线(Event Bus)或者 Prop(属性传递)的方式来实现。这里我们介绍两种常见的方法:
1. 使用事件总线(Event Bus)
创建一个全局的 Vue 实例作为事件总线,然后在 ChildComponentA
中发射一个事件,例如:
// 在 Parent 或者一个 Vue 插件中初始化事件总线
import { createAppBus } from '@/common/event-bus'
const appBus = createAppBus()
// ChildComponentA.vue
methods: {
openChildB() {
appBus.$emit('openChildB')
}
}
在 ChildComponentB
组件中,监听这个事件,并打开弹窗:
// ChildComponentB.vue
created() {
appBus.$on('openChildB', () => {
// 打开弹窗逻辑
this.showModal()
})
}
deactivated() {
appBus.$off('openChildB')
}
2. 通过 Prop 传递
如果这两个子组件在同一个父组件下,可以将 ChildComponentB
作为一个 prop 传入 ChildComponentA
,并在需要时调用其方法:
<!-- ParentComponent.vue -->
<template>
<ChildComponentA :childB="childB" />
</template>
<script>
export default {
components: {
ChildComponentA,
ChildComponentB,
},
data() {
return {
childB: null,
};
},
methods: {
openChildBModal() {
this.childB.openModal();
},
},
};
</script>
然后在 ChildComponentA
中调用:
<template>
<button @click="openChildBModal">打开 ChildB 弹窗</button>
</template>
相关推荐


















