VueJs 2.0 从孙子组件发出事件到他的祖父组件 [英] VueJs 2.0 emit event from grand child to his grand parent component

查看:84
本文介绍了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?

推荐答案

NEW ANSWER(2018 年 11 月更新)

我发现我们实际上可以通过利用孙子组件中的 $parent 属性来做到这一点:

I discovered that we could actually do this by leveraging the $parent property in the grand child component:

this.$parent.$emit("submit", {somekey: somevalue})

更干净、更简单.

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

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