Do custom events propagate up the component chain in Vue 3?

Viewed 1102

Custom events didn't propagate in Vue 2. Is there a change in Vue 3 because, as the following example shows, it looks like custom events bubble up the component chain:

const Comp1 = {
  template: `
    <button @click="this.$emit('my-event')">click me</button>
  `
}

const Comp2 = {
  components: {
    Comp1
  },
  template: `
    <Comp1/>
  `
}

const HelloVueApp = {
  components: {
    Comp2
  },
  methods: {
    log() {
      console.log("event handled");
    }
  }
}

Vue.createApp(HelloVueApp).mount('#hello-vue')
<script src="https://unpkg.com/vue@next"></script>

<div id="hello-vue" class="demo">
  <Comp2 @my-event="log"/>
</div>

2 Answers

Yes, by default they now fall through in VUE v3

You need to define inheritAttrs: false to prevent that

link to docs, though it doesn't seem to indicate that it affects the events too. It just mentions attributes, but events are part of attributes($attrs).

const Comp1 = {
  template: `
    <button @click="this.$emit('my-event')">click me</button>
  `
}

const Comp2 = {
  components: {
    Comp1
  },
  template: `
    <Comp1/>
  `,
  inheritAttrs: false 
}

const HelloVueApp = {
  components: {
    Comp2
  },
  methods: {
    log() {
      console.log("event handled APP");
    }
  }
}

Vue.createApp(HelloVueApp).mount('#hello-vue')
<script src="https://unpkg.com/vue@next"></script>

<div id="hello-vue" class="demo">
  <Comp2 @my-event="log"/>
</div>

You have to handle the event into Comp2 :

<Comp1 @my-event="this.$emit('my-event')"/>

Related