javascript - Do custom events propagate up the component chain in Vue 3? - Stack Overflow

Custom events didn't propagate in Vue 2. Is there a change in Vue 3 because, as the following exam

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 ponent chain:

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

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

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

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

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

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 ponent chain:

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

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

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

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

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

Share Improve this question edited Sep 8, 2022 at 11:27 Lee Goddard 11.2k5 gold badges51 silver badges69 bronze badges asked Oct 30, 2020 at 17:49 marzelinmarzelin 11.6k5 gold badges38 silver badges50 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 = {
  ponents: {
    Comp1
  },
  template: `
    <Comp1/>
  `,
  inheritAttrs: false 
}

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

Vue.createApp(HelloVueApp).mount('#hello-vue')
<script src="https://unpkg./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')"/>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745250960a4618674.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信