Call parent method from nested child in Vue

4.4k views Asked by At

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}`)
1

There are 1 answers

2
thanksd On BEST ANSWER

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.