VueJs 2.0将大孩子的事件发送到他的祖父组件 [英] VueJs 2.0 emit event from grand child to his grand parent component

查看:298
本文介绍了VueJs 2.0将大孩子的事件发送到他的祖父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Vue.js 2.0不会从一个大孩子向他的祖父组件发出事件。

It seems that Vue.js 2.0 doesn't emit events from a grand child to his grand parent component.

Vue.component('parent', {
  template: '<div>I am the parent - {{ action }} <child @eventtriggered="performAction"></child></div>',
  data(){
    return {
      action: 'No action'
    }
  },
  methods: {
    performAction() { this.action = 'actionDone' }
  }
})

Vue.component('child', {
  template: '<div>I am the child <grand-child></grand-child></div>'
})

Vue.component('grand-child', {
  template: '<div>I am the grand-child <button @click="doEvent">Do Event</button></div>',
  methods: {
    doEvent() { this.$emit('eventtriggered') }
  }
})

new Vue({
  el: '#app'
})

这个JsFiddle解决了问题起诉 https://jsfiddle.net/y5dvkqbd/4/ ,但通过发布两个事件:

This JsFiddle solves the issue https://jsfiddle.net/y5dvkqbd/4/ , but by emtting two events:


  • 一个从大孩子到中间组件

  • 然后从中间组件再次向大父母发送

添加此中间事件似乎是重复且不必要的。有没有办法直接向祖父母发出我不知道的事情?

Adding this middle event seems repetitive and unneccessary. Is there a way to emit directly to grand parent that I am not aware of?

推荐答案

Vue社区普遍赞成使用Vuex解决这类问题。对Vuex状态进行了更改,DOM表示只是从那里流出,在很多情况下消除了事件的需要。

The Vue community generally favors using Vuex to solve this kind of issue. Changes are made to Vuex state and the DOM representation just flows from that, eliminating the need for events in many cases.

除此之外,重新发布可能是下一个最好的选择,最后你可以选择使用事件总线,详见其他高度回答这个问题的答案。

Barring that, re-emitting would probably be the next best choice, and lastly you might choose to use an event bus as detailed in the other highly voted answer to this question.

下面的答案这是我对这个问题的原始答案,并不是我现在采取的方法,对Vue有更多的经验。

The answer below is my original answer to this question and is not an approach I would take now, having more experience with Vue.

这在这种情况下,我可能不同意Vue的设计选择并使用DOM。

This is a case where I might disagree with Vue's design choice and resort to DOM.

grand-child 中,

methods: {
    doEvent() { 
        try {
            this.$el.dispatchEvent(new Event("eventtriggered"));
        } catch (e) {
            // handle IE not supporting Event constructor
            var evt = document.createEvent("Event");
            evt.initEvent("eventtriggered", true, false);
            this.$el.dispatchEvent(evt);
        }
    }
}

parent

mounted(){
    this.$el.addEventListener("eventtriggered", () => this.performAction())
}

否则,是的,你必须重新发射或使用总线。

Otherwise, yes, you have to re-emit, or use a bus.

注意:我在doEvent方法中添加了代码来处理IE;该代码可以以可重用的方式提取。

Note: I added code in the doEvent method to handle IE; that code could be extracted in a reusable way.

这篇关于VueJs 2.0将大孩子的事件发送到他的祖父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆