首页 > 解决方案 > Vue,如何从父级中的两个子组件监听相同的事件?

问题描述

<template id="parentComp">
<child-comp-1 @customEvent="handler"/>
<child-comp-2 @customEvent="handler"/>
</template>

由于我收到相同的事件并为这两个事件使用相同的事件处理程序,有没有办法共同收听它们,即我可以让事件像本地事件一样冒泡并使用类似的东西

 <template id="parentComp" @customEvent="handler">

标签: eventsvue.jsvue-componentevent-bubblingvue-events

解决方案


Other than just passing the event to the parent you can use an event bus. This article describes this principle well: https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

The idea is to use a shared Vue instance to handle events. You will then import this instance in different elements, the same way you would import a library.


推荐阅读