VueJS - Expose Child Component Functions and Properties to Parent
VueJS Single File Components are great way to organize your code. When a component becomes too large, we can split it into smaller components. We can also nest components inside other components. Sometimes we need to access child component functions and properties from parent component. In this article, we will see how to expose child component functions and properties to parent component in VueJS. This article focus on exposting functions and properties when using <script setup>
syntax.
Expose Child Component Functions and Properties to Parent
Components using <script setup>
are closed by default and cannot be accessed by parent component using template refs. To expose functions and properties to parent component, we can use defineExpose
function. Let’s see how to use it.
Expose Functions
Let’s create a child component called ChildComponent
that has a function to increment a counter. We will expose this function to parent component.
<script setup lang="ts">
import { ref } from "vue";
const counter = ref(0);
function increment() {
counter.value++;
}
defineExpose({
increment,
});
</script>
<template>
<div>
<p>Counter: {{ counter }}</p>
</div>
</template>
In the above code, we have a function called increment
that increments the counter
value. We have exposed this function using defineExpose
function. Now we can access this function from parent component using template refs.
Let’s see how to use this component in parent component.
<script setup lang="ts">
import { ref } from "vue";
const childComponentRef = ref();
function handleClick() {
childComponentRef.value?.increment();
}
</script>
<template>
<div>
<ChildComponent ref="childComponentRef" />
<button @click="handleClick">Increment Counter</button>
</div>
</template>
In the above code, we have a template ref called childComponentRef
that points to ChildComponent
. We have a button that calls handleClick
function when clicked. This function calls increment
function on childComponentRef
template ref. This will increment the counter value.
Similarly we can expose properties to parent component, all the refs will be automatically unwrapped.