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

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

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

3 回答 3

1

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.

于 2018-05-25T08:23:58.197 回答
1

从多个组件中收听。从根级别发出并监听事件

this.$root.$emit('myTestEvent',dataToBeSent);

现在您可以使用任何组件收听

mounted(){
    this.$root.$on('myTestEvent', (dataReceived) => {
       //...
    })
}
于 2019-10-25T12:28:52.440 回答
0

you can use $listeners for event bubbling. give you an example

Vue.component('inner-com',{
  template: '<div>inner component<button @click="innerClick">emit event</button></div>',
  methods: {
    innerClick () {
      this.$emit('inner-com-click-event');
    }
  }
})

Vue.component('middle-com',{
  template: '<div>middle component<inner-com v-on="$listeners"></inner-com></div>'
})

Vue.component('outer-com',{
  template: '<div>outer component<middle-com v-on="$listeners"></middle-com></div>'
})


var app = new Vue({
  el:'#app',
  methods: {
    eventHandler () {
      alert('event receved')
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <outer-com @inner-com-click-event="eventHandler"></outer-com>
</div>

于 2018-05-25T08:24:10.820 回答