简体   繁体   中英

Call parent method from nested child in Vue

I scaffolded a project from vue-cli using the webpack template.

Now in the App component I created a bootstrap modal dialog, which I want to reuse from the entire application. Along with that I also created one method in the App component called showMessage which actually does the work of showing the modal.

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.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM