在Vue中从嵌套子项调用父方法

时间:2017-09-06 15:54:46

标签: javascript vue.js vue-cli

我使用vue-cli模板从webpack搭建了一个项目。

现在在App组件中,我创建了一个bootstrap模式对话框,我想从整个应用程序中重用它。除此之外,我还在App组件中创建了一个名为showMessage的方法,它实际上完成了显示模态的工作。

现在考虑到我应该能够从任何组件中获取该方法,就像下面显示的那样一个坏主意?

this.$root.$children[0].showMessage('Message', `An email will be sent to ${this.form.email}`)

1 个答案:

答案 0 :(得分:2)

这是处理全球消息传递的一种脆弱方式。

至少在模态组件内部注册根组件上的事件:

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')

通过这种方式,您可以更好地分离问题。