Calling Methods from other Components in Vue

I just had a eureka moment. Although this blog might be short, it can save you tremendous time. Have you ever been working on a component or page in Vue and then realize that you need to change the state of another component using a method from that component? Unless you are storing this data in Vuex and using Vuex mutations, these methods can be difficult to access without prop drilling (essentially moving the state to a common parent component/page then sending the props/methods down to each child component).

Let’s say you have component A and component B which have no common parent component other than the ultimate parent of your application. If component B wants to use a method defined in component A, we would need to manage the state in the ultimate parent or in Vuex. This can be easily done. However, many times you are updating/debugging existing components that are not using Vuex to manage their state. In this case, what should we do? Rewrite all of our code? Instead, component B can indirectly call a method defined in component A by using an event listener in component A. When component A detects the event, component A can fire the event.

  1. Component A is shown below. component A has a local state with count: 1. It has a method called “incrementCount.” In the mounted() lifecycle hook, we write an event listener on the root that listens for a custom event called “incrementCountEvent.” When component A hears this custom event, it will fire incrementCount.
export default {
data(){
return {
count: 1
}
},
methods: {
incrementCount() {
this.count++
}
},
mounted(){
const thisInstance = this
this.$root.$on('incrementCountEvent', function(){
thisInstance.incrementCount()
})
}
}

2. Component B needs to “emit” our custom event called “incrementCountEvent.” When component A detects the event, it will fire incrementCount().

this.$root.$emit('incrementCountEvent')

Note, I still haven’t found an efficient way for component B to access component A’s local state. If anyone has any suggestions, please comment.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store