Subscribe on changes!

Component ref not available in the composition api

avatar
Feb 19th 2022

Version

3.2.31

Reproduction link

sfc.vuejs.org

Steps to reproduce

Clicking the button does not get the component ref.

What is expected?

Get component ref normally

What is actually happening?

Can't get component ref

avatar
Feb 19th 2022

I can only reproduce it in SFC Playground.:dizzy_face:

avatar
Feb 19th 2022

you are getting it, you just can't console.log the object.

try for example console.log(componentRef.value.$) or console.log(componentRef.value.$.ctx)

avatar
Feb 19th 2022

you are getting it, you just can't console.log the object.

try for example console.log(componentRef.value.$) or console.log(componentRef.value.$.ctx)

This method can access the subcomponent instance, but there are no subcomponent-related methods.

avatar
Feb 19th 2022

I can only reproduce it in SFC Playground.😵

You can try it in the project where I found this problem. https://github.com/Hongbusi/vue-element-admin/blob/master/src/views/login/components/login-panel.vue#L40

avatar
Feb 19th 2022

You might not be able to console log inside the SFC playground but the variable is set, as @lidlanca pointed out.

The problem comes https://github.com/vuejs/repl/blob/main/src/output/srcdoc.html#L134. Maybe it's worth doing a try-catch there. You should open a PR @Hongbusi

avatar
Feb 20th 2022

The code in the SFC playground is just a simple implementation.

The real find is in this place https://github.com/Hongbusi/vue-element-admin/blob/master/src/views/login/components/login-panel.vue#L40. @posva

avatar
Feb 20th 2022

@Hongbusi I re-created your demo in Stackblitz and it works fine. See it here

So yeah the issue happens only in SFC playground

avatar
Feb 20th 2022

When I click on the button, the output is this. And I can't access the methods defined inside the childComponent properly.

image

Is there something wrong with the way I'm using it? See it here @Rolanddoda

avatar
Feb 20th 2022

@Hongbusi if you don't use the SFC playground but you instead use Stackblitz demo here you will see that the Vue instance is correctly displayed:

image

avatar
Feb 20th 2022

@Rolanddoda The screenshot just now is the result of my local printout.

avatar
Feb 20th 2022

When a method exists in a child component, it is not accessible via ref in the parent component.

Child component:

<script setup>
const action = () => {
  console.log('action')
}
</script>

Parent component:

<script setup>
const handleClick = () => {
  componentRef.value.action() // error
}
</script>
avatar
Feb 20th 2022

Thank you. @lidlanca