【问题标题】:Does custom events propagate up the component chain in Vue 3?自定义事件是否会在 Vue 3 中向上传播组件链?
【发布时间】:2021-02-13 05:09:42
【问题描述】:

自定义事件没有在 Vue 2 中传播。Vue 3 中是否有变化,因为如下例所示,自定义事件看起来像在组件链中冒泡:

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>

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    是的,默认情况下它们现在在 VUE v3 中失效

    您需要定义inheritAttrs: false 以防止这种情况发生

    link to docs,尽管它似乎并不表明它也会影响事件。它只是提到了属性,但事件是属性的一部分($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>

    【讨论】:

    • 附带说明:此解决方案之所以有效,是因为 listeners are now passed as part of $attrs 这就是他们现在失败的原因。因为inheritAttrs默认为truesince version 2
    • 您解释了为什么我的代码有效,但我认为我的问题的答案应该是否定的,自定义事件不会传播并且代码有效只是因为默认情况下将侦听器向下传递(在 $attrs 中) Vue 3.
    • 当然,我会强调答案的那部分
    • @Daniel 如果我们向 Comp1 添加任何发射,这将停止工作。在这种情况下,my-event 不会被传播。谁能解释一下原因?
    • 这让我发疯了,谢谢@Daniel!
    【解决方案2】:

    您必须将事件处理到 Comp2 中:

    &lt;Comp1 @my-event="this.$emit('my-event')"/&gt;

    【讨论】:

      猜你喜欢
      • 2010-11-13
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2020-06-09
      • 2020-12-06
      • 1970-01-01
      • 2014-02-12
      相关资源
      最近更新 更多