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"
)
}
}
})
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"
)
}
}
})
Share
Improve this question
edited Jul 11, 2020 at 3:36
tony19
138k23 gold badges277 silver badges346 bronze badges
asked Jul 10, 2020 at 17:17
AxelAxel
5,12118 gold badges75 silver badges146 bronze badges
0
3 Answers
Reset to default 11In 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"
)
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"
)
}
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>
}