[英]Call parent method from nested child in Vue
I scaffolded a project from vue-cli
using the webpack
template. 我使用
webpack
模板webpack
了来自vue-cli
的项目。
Now in the App
component I created a bootstrap modal dialog, which I want to reuse from the entire application. 现在,在
App
组件中,我创建了一个引导模式对话框,我想在整个应用程序中重用该对话框。 Along with that I also created one method in the App
component called showMessage
which actually does the work of showing the modal. 除此之外,我还在
App
组件中创建了一个名为showMessage
方法,该方法实际上完成了显示模式的工作。
Now considering that I should be able to reach that method from any component, is calling like what is shown below a bad idea? 现在考虑到我应该能够从任何组件访问该方法,像下面显示的那样调用是一个坏主意吗?
this.$root.$children[0].showMessage('Message', `An email will be sent to ${this.form.email}`)
That is a fragile way to handle global messaging. 这是处理全局消息传递的脆弱方法。
At least register an event on the root component from inside the modal component: 至少从模态组件内部在根组件上注册一个事件:
methods: {
showMessage(message) {
// your code to display the message
}
},
created() {
this.$root.$on('showMessage', this.showMessage)
},
destroyed() {
this.$root.$off('showMessage', this.showMessage)
}
Then you can use this.$root.$emit('showMessage', 'foo message')
to display a message from anywhere within the scope of that root component. 然后,您可以使用
this.$root.$emit('showMessage', 'foo message')
从该根组件范围内的任何位置显示一条消息。
Even better might be to create an event bus: 更好的做法可能是创建事件总线:
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')
This way, you have a slightly better separation of concerns. 这样,您的关注点分离会更好一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.