How to Pass a Function as a Prop in Vue

  1. Passing a function as a prop
  2. React vs Vue
  3. Using events
  4. Sources

It is cmmon to pass strings, arrays, numbers, and objects as props in Vue, but is it possible to pass a function as a prop?

While the answer is positive, this is widely seen as a bad idea. Instead, there is a feature built in Vue that is designed for this purpose.

Passing a function as a prop

Taking a function or a method and passing it down to a child component as a prop is quite straightforward. In fact, it is exactly the same as passing any other variable:

1
2
3
4
5
6
7
8
9
<template>
<ChildComponent :function="myFunction" />
</template>

<script setup>
const myFunction () => {
// ...
}
</script>

But as I mentioned earlier, this is something you should not ever be doing in Vue.

Why?

Well, Vue has something better…

React vs Vue

If you’re coming from React, you’re accustomed to frequently passing down functions. In React, you pass a function from a parent to a child component so that the child can communicate back to the parent. Props and data flow down, while function calls flow up.

In Vue, however, the mechanism for child-to-parent communication is different. Vue uses events for this purpose. This approach is similar to how the DOM works, offering more consistency with the browser compared to React. Elements in Vue can emit events, and these events can be listened to.

Therefore, while it might be tempting to pass functions as props in Vue, it is considered an anti-pattern.

Using events

Events are the method used for communicating with parent components in Vue. Here is a brief example to demonstrate how events function. First, we’ll create a child component that emits an event upon creation:

1
2
const emit = defineEmits(["created"]);
emit("created");

In our parent component, we will listen to that event:

1
2
3
4
5
6
7
8
9
<template>
<ChildComponent @created="handleCreate" />
</template>

<script setup>
const handleCreate = () => {
console.log("Child has been created.");
};
</script>

There is much more that can be done with events, and this only covers the basics. I highly recommend checking out the official Vue documentation to learn more about events—it’s definitely worth reading!

Sources