Vue 3 + Typescript: Call method in child component from parent

Vue 3 + Typescript: Call method in child component from parent

2023-05-05
2 min read

Overview

Occasionally, it is required to access methods in child component from an outside component. The Emit events can solve most communication between child and parent component. However, it is hard to control child component in detail. In addition, This article will use <script setup> along with Typescript. If you're using JavaScript, you need to ignore syntax declaring types.

defineExpose()

The Vue defineExpose() macro allows to access properties in component from parent component. The Component will only export variables or functions that you write in Object parameter in defineExpose(). The Parent component only can use variables or functions defined in defineExpose().

Child component

vue
<script setup lang="ts">
import { ref } from 'vue'

const count = ref(0)

const increaseCount = () => {
  count.value++
}

const setCount = (newCount: number) => {
  count.value = newCount
}

defineExpose({
  count,
  increaseCount,
  setCount,
})
</script>

In your child component, import defineExpose() API. Add variables or methods that you would like to export into parameter. As it's mentioned, only properties in defineExpose() are accessible from outside of component.

Parent component

vue
<script setup lang="ts">
import { ref } from 'vue'
import ChildComponent from './Child.vue'

const childRef = ref<InstanceType<typeof ChildComponent> | null>(null)

const handleIncrease = () => {
  childRef.value?.increase()
}

const handleSetZero = () => {
  childRef.value?.setCount(0)
}
</script>
<template>
  <div>
    <div>
      Parent
      <button @click="handleIncrease">
        increase
      </button>
      <button @click="handleSetZero">
        Set Zero
      </button>
    </div>
    <child-component ref="childRef" />
  </div>
</template>

Declaring Template ref is necessary to use properties in child component. In order to get instance type of child component, you have to set InstanceType<typeof ChildComponent | null for type of Template ref and null for default value. It will indicates type of component and prevent error lines for variables and functions that is exported.

ref

Free open source project made by Youngjin