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 两个事件:
- 一个从孙子到中间组件
- 然后再次从中间组件发射到祖父母
添加这个中间事件似乎是重复的和不必要的。有没有办法直接发射给我不知道的祖父母?
原文由 BassMHL 发布,翻译遵循 CC BY-SA 4.0 许可协议
新答案(2018 年 11 月更新)
我发现我们实际上可以通过利用大子组件中的
$parent
属性来做到这一点:更干净,更简单。