Execute a function from child component in Vue
Find out how we can execute a function in the parent component from the child component using emit function 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.
<u>Child Component:</u>
<template> <div> <button @click="myFunction">Click</button> </div> </template> <script> export default { props: { myFunction: { type: Function }, }, }; </script>
So in <u>parent component</u> 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
Related Posts
How to pass data from parent component to child using props in Vue
Find out how to send data from parent component to child component using props in Vue.
Pass multiple objects as props in Vue
Short tutorial on how to pass multiple objects as props to a child component from parent in vue using v-for directive.
How to pass multiple props to component in Vue
Short article on how to pass multiple props to a component in vue using v-bind.
How to listen for props changes in VueJS?
This article is about how to listen for prop changes in vue. We will be vuejs watcher or watch property to listen for any changes in props.
