Obama
Obama

Reputation: 2612

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

Upvotes: 3

Views: 4962

Answers (3)

Mervyn
Mervyn

Reputation: 583

I found a solution in this issure : https://github.com/vuejs/core/issues/4397.

Use volar v0.31.1, You can use const myRef = ref<null | InstanceType<typeof MyComponent>>(null);

Upvotes: 0

Obama
Obama

Reputation: 2612

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

Upvotes: 1

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23490

As far as I can see your code is fine, take a look here pls.

Upvotes: 0

Related Questions