How to call a method in a child component with Vue.js?

Sometimes, we want to call a method in a child component with Vue.js.

In this article, we’ll look at how to call a method in a child component with Vue.js.

How to call a method in a child component with Vue.js?

To call a method in a child component with Vue.js, we can pass in a prop from the parent component to its child.

Then in the child component, we watch the prop’s value and run the method we want.

For instance, we write

<script>
export default {
  //...
  props: ["testProp"],
  methods: {
    sayHello() {
      alert("hello");
    },
  },
  watch: {
    testProp(newVal, oldVal) {
      this.sayHello();
    },
  },
};
</script>

in the child component to register the testProp prop and add the sayHello method.

We also add a watcher for testProp in watch which calls sayHello when testProp changes value.

Then in the parent component, we write

<template>
  <div>
    <ChildComponent :testProp="trigger" />
  </div>
</template>

<script>
export default {
  //...
  data() {
    return {
      trigger: 0,
    };
  },
};
</script>

to add the ChildComponent and set the testProp prop to trigger.

And we change the trigger value to run sayHello.

Conclusion

To call a method in a child component with Vue.js, we can pass in a prop from the parent component to its child.

Then in the child component, we watch the prop’s value and run the method we want.