javascript - 自定义事件是否会在 Vue 3 中向上传播组件链?

标签 javascript vue.js vuejs3

自定义事件没有在 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>

最佳答案

是的,默认情况下它们现在在 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>

关于javascript - 自定义事件是否会在 Vue 3 中向上传播组件链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64613446/

相关文章:

typescript - 使用脚本设置和 Typescript 禁用属性继承/设置组件选项

javascript - 如何检查从 javascript 正确加载的网络资源?

javascript - 如何使用createElement创建新表?

javascript - Vue 未使用 Axios 请求中的数据从数组更新 Vuetify 数据表

vue.js - Vue 3图表js导致无法读取null的属性(读取 'getContext')?

typescript - 类型错误 : EventEmitter is not a constructor at new MapboxGeocoder

javascript - 无法让 jQuery 悬停与 if 语句一起使用

javascript - js 函数不在 IE 8 中的数组元素中运行

javascript - 绑定(bind) src 时视频或 iframe 标签无法正常工作

vue.js - 在 django 管理中使用 vue.js