[Vuejs]-How to properly use childs component methods in parent in VUE?

2đź‘Ť

When you find yourself calling methods from another (child) component you should rethink your architecture. Vue components are reusable parts you can use to assemble a view, they are not meant to share javascript logic across your application. If you want to do that you’re better off writing a module and importing its functions in your parent Vue file. The way you “communicate” with your child components properly is by prop-bindings, which contain data and can re-trigger the render loop of your child component. Communicating from the child to the parent is done by dispatching events. You never want to share logic between the two.

Regardless here’s how you can do it anyway:

You have to have an element of your child component in the parent’s template, otherwise it wont be mounted and its methods can’t be accessed:

<component-image-upload ref="image" />

Then you can call any method on that component by using its ref:

createImage (page) {
  this.$refs.image.myMethod('this is how you call it from parent')
}

0đź‘Ť

The best way to do this is Custom Event

You can trigger any event from your component to the #root element which you have loaded in vue instance.

$emit('event-name') can be used to trigger the event!!

I hope this helps 🙂

Leave a comment