[英]Call parent method from nested child in Vue
我使用webpack
模板webpack
了来自vue-cli
的项目。
现在,在App
组件中,我创建了一个引导模式对话框,我想在整个应用程序中重用该对话框。 除此之外,我还在App
组件中创建了一个名为showMessage
方法,该方法实际上完成了显示模式的工作。
现在考虑到我应该能够从任何组件访问该方法,像下面显示的那样调用是一个坏主意吗?
this.$root.$children[0].showMessage('Message', `An email will be sent to ${this.form.email}`)
这是处理全局消息传递的脆弱方法。
至少从模态组件内部在根组件上注册一个事件:
methods: {
showMessage(message) {
// your code to display the message
}
},
created() {
this.$root.$on('showMessage', this.showMessage)
},
destroyed() {
this.$root.$off('showMessage', this.showMessage)
}
然后,您可以使用this.$root.$emit('showMessage', 'foo message')
从该根组件范围内的任何位置显示一条消息。
更好的做法可能是创建事件总线:
Vue.prototype.$bus = new Vue();
methods: {
showMessage(message) {
// your code to display the message
}
},
created() {
this.$bus.$on('showMessage', this.showMessage)
},
destroyed() {
this.$bus.$off('showMessage', this.showMessage)
}
this.$bus.$emit('showMessage', 'foo message')
这样,您的关注点分离会更好一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.