Execute a function from child component in Vue

In this article, we will learn how to execute a function from a child component in Vue Js.

In Vue, we want to execute a parent component function from a child component, we usually try to pass the function as a prop to the child.

For example, if we want to run a function called printText(), we will define a prop in our child component and pass the function from the parent component.

Child Component:

<template>
    <div>
        <button @click="myFunction">Click</button>
    </div>
</template>
<script>
export default {
  props: {
    myFunction: { type: Function },
  },
};
</script>

So in parent component we pass the child:

<template>
  <div id="app">
    <ChildComponent :myFunction="printText" />
  </div>
</template>

<script>
export default {
  methods: {
    printText() {
      alert("clicked from child component");
    },
  },
};
</script>

However, even though this works perfectly, Vue provides us a way to do this task in a much easier way using the $emit function.

Execute a function from a child component using $emit function

The Vue $emit function lets us emit or pass a custom event from a child component to its parent.

So to execute a function from the child component, we just have to pass an event to the parent component and this custom event will run the function.

<template>
  <div>
    <button @click="handleFn">Click</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleFn() {
      this.$emit("runfunction");
    },
  },
};
</script>

Here, we have emit a custom event called ‘runfunction‘ when we click the button.

And in the parent component, we listen to this event.

<template>
  <div id="app">
    <ChildComponent @runfunction="printText" />
  </div>
</template>

<script>
export default {
  methods: {
    printText() {
      alert("clicked from child component");
    },
  },
};
</script>

Here, we are listening to the event, and when the button is clicked in the child component, the printText() function is executed in the parent component.

So, this is how we can run a function without even passing the function as a prop in Vue.


Related Articles:

How to pass data from parent component to child using props in Vue

How to pass data from child to parent component in Vue

Pass multiple objects as props in Vue

How to set default value for prop function in VueJS

Scroll to Top