Skip to content
Advertisement

Vue 3 refs is undefined in render function

I have a simple Vue component with root element as ref="divRef". However, in onMounted function, divRef.value returns undefined. Any help will be appreciated.

import { defineComponent, onMounted, ref, Ref, h } from "vue"

export default defineComponent({
    setup(props, context) {
        const divRef = ref() as Ref<HTMLElement>

        onMounted(() => {
            console.log(divRef.value) // undefined
        })

        return () => {
            return h(
                "div",
                {
                    ref: "divRef"
                },
                "This is a div"
            )
        }
    }
})

Advertisement

Answer

In your render function, pass the divRef itself, not a string:

return h(
    "div",
    {
        //ref: "divRef"   // DON'T DO THIS
        ref: divRef
    },
    "This is a div"
)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement