'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"
)
}
}
})
Solution 1:[1]
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"
)
Solution 2:[2]
div elements do not have value attribute by default if you are trying to access "This is a div" (text within the div) you should use innerText property like this: divRef.innerText.
Update
According to docs, you have to pass the ref itself as the ref in your return element to get access to $el in Vue 3. So your code should be something like this:
return () => {
return h(
"div", {
ref: divRef
},
"This is a div"
)
}
Solution 3:[3]
if you are use jsx in render function. you also need pass the divRef itself, can't by string.
set() {
const divRef = ref() as Ref<HTMLElement>
return () => <div ref={divRef}></div>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tony19 |
| Solution 2 | |
| Solution 3 | ??? |
