Search code examples
javascriptvue.jsvuejs3vue-sfc

Vue 3 defineExpose doesn't expose child method or property


I have a Parent and child components as the following :

Parent Component :

<script setup>
import ChildComp from '@/components/ChildComp.vue'
import { ref, computed } from 'vue'

const childComp = ref(null)
const clickMe = () => {
    console.log(childComp.value.selectedRadio) // <====== UNDEFINED
    childComp.value.hello() // <======= RETURNS hello is not a function
};
</script>

<template>
  <ChildComp ref="childComp" />
  <button @click="clickMe()" type="button">Click Me!</button>
</template>

Child component :

<script setup>
import { ref } from 'vue'

const selectedRadio = ref("")
selectedRadio.value = "test"

const hello = () => {
   console.log("hey from child");
};

defineExpose({
 hello,
 selectedRadio,
});
</script>

<template>
  <div>
    <h3>Hi! I am the child component</h3>
  </div>
</template>

As described in code, when the button is clicked I have the following errors :

console.log(childComp.value.selectedRadio) // <====== UNDEFINED
 childComp.value.hello() // <======= RETURNS hello is not a function

Knowing that the childComp returns correctly the component Object and when accessing childComp.value.$.exposed I can see both selectedRadio property and hello function.

Vue version : 3.2.45

Could you please help me?

Thank you


Solution

  • I solved the issue by adding : @vue/compiler-sfc": "^3.2.45 in my devDependencies