Ref not working on custom component in Vue3
Asked Answered
R

1

10

I'm using Vue3 with the composition API. In a form-component I put ref's on each field (child-component).

For some reason the ref's of the custom components are different from ref's for Quasar components.

When I console.log a ref to a custom component I get this in DevTools:

Proxy {__v_skip: true}   

(without any properties in Target)

while a ref to a Quasar components gives this :

Proxy {…}  

(with all properties of the component in Target)

For this reason I can't use the ref to access properties or methods of these child components.

I have no idea what __v_skip even means. My custom components are defined with script setup, could that be a reason?

Any idea how to fix this?

UPDATE If I use defineExpose in the child components for the properties and methods I want to access from outside with a ref, it does work. Not really handy though, since these components have lots of props.

Ruffian answered 9/2, 2022 at 15:32 Comment(1)
You're addressing the wrong thing. If you have a problem consider explaining it and providing stackoverflow.com/help/mcve for it. You shouldn't pay attention to internal Vue properties. There's a possibility that different representation of refs indicates that something wrong was done with them, but there are not enough reasons to consider this.Justiciable
S
15

Seem likes currently you cannot access the custom component by ref, if your component is written by Composition API (<script setup>). But you can try the way I mention underneath.

In the Vue 3 doc, there are some lines mentioned this behavior:

An exception here is that components using <script setup> are private by default: a parent component referencing a child component using <script setup> won't be able to access anything unless the child component chooses to expose a public interface using the defineExpose macro

Read more here: Vue 3 - Ref on Component

That means if you want to access anything from the custom component, your component has to expose that information. I think it's because in Vue 3 you don't need to have root component anymore, so if you define a ref, Vue does not know what the component you want to ref to.

But...

You can try to use yourRef.value.$el, maybe it will help.

Example:

// Parent.vue
<template>
  <Child ref="childRef">
</template>

<script setup lang="ts">
// Import things...

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

onMounted(() => {
  console.log(childRef.value.$el); 
});
</script>
Saber answered 19/3, 2022 at 13:57 Comment(1)
Only the original vue defineExpose method worksGrab

© 2022 - 2024 — McMap. All rights reserved.