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.
JavaScript
x
23
23
1
import { defineComponent, onMounted, ref, Ref, h } from "vue"
2
3
export default defineComponent({
4
setup(props, context) {
5
const divRef = ref() as Ref<HTMLElement>
6
7
onMounted(() => {
8
console.log(divRef.value) // undefined
9
})
10
11
return () => {
12
return h(
13
"div",
14
{
15
ref: "divRef"
16
},
17
"This is a div"
18
)
19
}
20
}
21
})
22
23
Advertisement
Answer
In your render
function, pass the divRef
itself, not a string:
JavaScript
1
9
1
return h(
2
"div",
3
{
4
//ref: "divRef" // DON'T DO THIS
5
ref: divRef
6
},
7
"This is a div"
8
)
9