似乎 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 viav-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/