我有一个简单的Vue组件,其根元素为ref="divRef"。但是,在onMounted函数中,divRef.value返回未定义。任何帮助将不胜感激。

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"
            )
        }
    }
})

最佳答案

render函数中,传递divRef本身,而不是字符串:

return h(
    "div",
    {
        //ref: "divRef"   // DON'T DO THIS
        ref: divRef
    },
    "This is a div"
)

关于javascript - Vue 3引用在渲染函数中未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62839300/

10-10 23:13