javascript - VueJs 2.0 将事件从孙子发送到他的祖父组件

标签 javascript vuejs2 vue.js

似乎 Vue.js 2.0 不会将事件从孙子组件发送到他的祖父组件。

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/ , 但通过 emtting 两个事件:

  • 一个从孙子到中间部分
  • 然后再次从中间组件发射到祖 parent

添加此中间事件似乎是重复且不必要的。有没有一种我不知道的直接发送给祖 parent 的方法?

最佳答案

Vue 2.4 引入了一种使用 vm.$listeners

轻松向上传递事件的方法

来自 https://v2.vuejs.org/v2/api/#vm-listeners :

Contains parent-scope v-on event listeners (without .native modifiers). This can be passed down to an inner component via v-on="$listeners" - useful when creating transparent wrapper components.

查看下面在 child 模板的 grand-child 组件中使用 v-on="$listeners" 的片段:

Vue.component('parent', {
  template:
    '<div>' +
      '<p>I am the parent. The value is {{displayValue}}.</p>' +
      '<child @toggle-value="toggleValue"></child>' +
    '</div>',
  data() {
    return {
      value: false
    }
  },
  methods: {
    toggleValue() { this.value = !this.value }
  },
  computed: {
    displayValue() {
      return (this.value ? "ON" : "OFF")
    }
  }
})

Vue.component('child', {
  template:
    '<div class="child">' +
      '<p>I am the child. I\'m just a wrapper providing some UI.</p>' +
      '<grand-child v-on="$listeners"></grand-child>' +
    '</div>'
})

Vue.component('grand-child', {
  template:
    '<div class="child">' +
      '<p>I am the grand-child: ' +
        '<button @click="emitToggleEvent">Toggle the value</button>' +
      '</p>' +
    '</div>',
  methods: {
    emitToggleEvent() { this.$emit('toggle-value') }
  }
})

new Vue({
  el: '#app'
})
.child {
  padding: 10px;
  border: 1px solid #ddd;
  background: #f0f0f0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <parent></parent>
</div>

关于javascript - VueJs 2.0 将事件从孙子发送到他的祖父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42615445/

相关文章:

javascript - 当我更新Vuex状态时,V-snackbar不显示

javascript - 如何使用Nuxt正确加载js文件?奇怪的行为

javascript - 如何避免自定义指令的[Vue warn]?

javascript - 机器人问题与功能 bot.reply (Discord)

javascript - 很难使用 flowtype.js 使我的文本更具响应性

vue.js - 为什么我在 v-on 属性值中不需要 `this`?

node.js - Vuejs错误: Rule can only have one resource source (provided resource and test + include + exclude)

javascript - Cognito getId : NotAuthorizedException: Invalid login token. 不是有效的 OpenId Connect 身份 token

javascript - Echo JS onclick 填充功能 AJAX 不工作

vue.js - v-show 不适用于 Prop