Reputation: 5121
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"
)
}
}
})
Upvotes: 5
Views: 13861
Reputation: 141
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>
}
Upvotes: 1
Reputation: 10520
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
.
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"
)
}
Upvotes: 5
Reputation: 138326
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"
)
Upvotes: 11