【问题标题】:Call parent method from nested child in Vue从Vue中的嵌套子调用父方法
【发布时间】:2018-02-15 04:54:20
【问题描述】:

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

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

现在考虑到我应该能够从任何组件访问该方法,像下面显示的那样调用是一个坏主意吗?

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

【问题讨论】:

  • 使用 $root 或 $parent 总是不好的做法。

标签: javascript vue.js vue-cli


【解决方案1】:

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

至少从模态组件内部在根组件上注册一个事件:

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

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

【讨论】:

  • 太棒了。这就像一个魅力。一个简单的问题是,是否应该将事件命名为 app::showMessage 之类的名称,以便仅将其范围用于我的应用程序?
  • 是的,这是有道理的。或者你可以创建一个事件总线(见我的编辑)
猜你喜欢
  • 2018-05-27
  • 1970-01-01
  • 2021-02-03
  • 2022-06-30
  • 2020-05-06
  • 2021-08-28
  • 2016-11-07
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多