首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Vue js 2在组件子组件链上冒泡事件?

如何使用Vue js 2在组件子组件链上冒泡事件?
EN

Stack Overflow用户
提问于 2017-02-04 00:51:23
回答 6查看 27.7K关注 0票数 26

我的vue应用程序使用:

component -由component-child组成的父组件

在component-parent中,我有按钮,当有人点击一个按钮时,我想要发出一个事件,以便由vue处理并传递给另一个组件

到目前为止,我所做的是:

代码语言:javascript
复制
var vm = new Vue({
    el: '#app',
    methods: {
        itemSelectedListener: function(item){
            console.log('itemSelectedListener', item);
        }
    }
});

Vue.component('component-child', {
    template: ' <span  v-on:click="chooseItem(pty )" >Button  </span>',
    methods: {
        chooseItem: function(pty){
            console.log(pty);
            this.$emit('itemSelected', {
                'priority' : pty
            });
        }
    }
});

Vue.component('component-parent', {
    template: '<component-child  v-for="q in items" ></component-child>'
});

HTML:

代码语言:javascript
复制
<component-parent v-on:itemSelected="itemSelectedListener"  ></component-parent>

它到达了我的console.log(pty);线路,但似乎this.$emit('itemSelected'无法接通:

代码语言:javascript
复制
console.log('itemSelectedListener', item); // this is not going to be called...

一个提示?

我应该从子->父->Vue-instance中冒泡事件吗?(我也试过了,但没有成功)

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2017-02-04 04:02:03

您的component-parent模板有一个问题,因为它试图呈现多个子组件。Vue通常在组件中需要一个根div,因此您需要将其包装在div或其他标记中。

代码语言:javascript
复制
<div>
    <component-child  v-for="q in items"></component-child>
</div>

第二件要指出的事情是,你从子组件中发出一个事件,然后在根组件中监听它。

代码语言:javascript
复制
Root //but you listen to the event up here 1 level above
 Component 1 //you should listen to the event here
  Component 2 //your try to emit it from here

这里有两个选项。从component-child发出侦听component-parent中的事件,然后向上传播该事件。小提琴https://jsfiddle.net/bjqwh74t/29/

第二种选择是注册一个全局的所谓的bus,它是一个空的vue实例,当您想要在非子-父组件之间进行通信时,可以使用它。小提琴https://jsfiddle.net/bjqwh74t/30/

通常,在父组件和子组件之间,您可以通过从子组件发出事件并使用v-on:event-name="handler"侦听父组件来直接使用事件,但是对于组件之间有更多级别的情况,您可以使用第二种方法。

第一种情况的文档链接:https://vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events

第二种情况的文档链接:https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

PS:喜欢使用烤肉串大小写的事件名称,这意味着你写-而不是大写字母。用大写字母书写可能会导致奇怪的情况,在这种情况下,您的事件不会在根中被捕获。

票数 23
EN

Stack Overflow用户

发布于 2018-12-15 03:35:13

无论如何,您可以使用浏览器的事件API。它需要比Vue内置的东西更多的脚本,但它也可以让你绕过这些冒泡的问题(并且与创建“总线”的代码量大致相同,正如公认的答案一样)。

在子组件上:

代码语言:javascript
复制
this.$el.dispatchEvent(new CustomEvent('itemSelected', { detail: { 'priority' : pty }, bubbles: true, composed: true });

在父组件上,在mounted生命周期零件中:

代码语言:javascript
复制
mounted() {
    this.$el.addEventListener('itemSelected', e => console.log('itemSelectedListener', e.detail));
}
票数 18
EN

Stack Overflow用户

发布于 2018-06-15 21:10:55

有点晚了,但我是这么做的:

组件-子组件:

代码语言:javascript
复制
this.$root.$emit('foobar',{...});

组件-父组件:

代码语言:javascript
复制
this.$root.$on('foobar')
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42029150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档