在Vue 2.0中,文档和其他人清楚地表明,从父母到孩子的沟通是通过道具进行的.
父母如何告诉孩子一个事件是通过道具发生的?
我应该只看一个名为事件的道具吗?这感觉不对,也没有替代方案($emit/ $on是孩子到父母,而中心模型是远程元素).
我有一个父容器,它需要告诉它的子容器,可以在API上使用某些操作.我需要能够触发功能.
假设我有一个想要向一个曾祖父母发送消息的子组件,代码将是这样的,如果我错了,请纠正我:
Vue.component('child', {
template: `<div v-on:click="clicked">Click me</div>`,
methods: {
clicked: function () {
this.$emit('clicked', "hello")
},
},
});
Vue.component('parent', {
template: `<child v-on:clicked="clicked"></child>`,
methods: {
clicked: function (msg) {
this.$emit('clicked', msg)
},
},
});
Vue.component('grandparent', {
template: `<parent v-on:clicked="clicked"></parent>`,
methods: {
clicked: function (msg) {
this.$emit('clicked', msg)
},
},
});
Vue.component('greatgrandparent', {
template: `<grandparent v-on:clicked="clicked"></grandparent>`,
methods: {
clicked: function (msg) {
console.log('message from great grandchild: ' + msg);
},
},
});
Run Code Online (Sandbox Code Playgroud)
是否有可能直接拦截来自孩子的消息并调用曾祖父母中的点击功能而无需在每个父母处设置传递回调?
我知道我可以使用自定义数据总线,https: //vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication,但由于我的组件已经有了亲子关系,我不应该能够以更简单的方式通知祖父母?