Javascript 从Vue中的嵌套子对象调用父方法

Javascript 从Vue中的嵌套子对象调用父方法,javascript,vue.js,vue-cli,Javascript,Vue.js,Vue Cli,我使用webpack模板从vue cli构建了一个项目 现在在App组件中,我创建了一个引导模式对话框,我想从整个应用程序中重用它。除此之外,我还在App组件中创建了一个名为showMessage的方法,该方法实际上完成了显示模态的工作 现在考虑到我应该能够从任何组件获得该方法,下面所示的调用是不是一个坏主意 this.$root.$children[0].showMessage('Message', `An email will be sent to ${this.form.email}`)

我使用
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();


这样,您可以更好地分离关注点。

使用$root或$parent始终是一种糟糕的做法。太棒了。这很有魅力。一个简单的问题是,是否应该将事件命名为类似于
app::showMessage
的名称,以便为我的应用程序确定范围?是的,这很有意义。或者您可以创建事件总线(请参见我的编辑)
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')