today, I used ref
function to get a reference to an element and got a problem that the value of this ref
object is null when using it in onMounted()
function. Then, to solve this problem, I search for ref
on official vue website, but I found a new function: useTemplateRef()
instead of ref
. At this point, I know the vue version has become 3.5+. Vue team has replaced ref
fucntion with useTemplateRef()
to get element references, but when I use this new fucntion in the code ref
function is used, it still doesn't work. After Thinking a lot of time, I finally found the problem:
<script setup>
/*** code *** /
........code
function initThree() {
let container= useTemplateRef('container');
}
........code
onMounted(()=>{
container.appendChild(...);
})
/*** code *** /
</script>
this is because the setup
syntactic sugar puzzles me. let's turn back the essence of setup
:
<script>
/*** code *** /
........code
setup() {
function initThree() {
let container= useTemplateRef('container');
}
return { container };
}
........code
onMounted(()=>{
container.appendChild(...);
})
/*** code *** /
</script>
here I defined container variable inside an inner function, so that it cannot be accessed in the top scope of setup()
.
Top comments (1)
Oh yeah, I’ve had this issue too. The problem here is scoping in
<script setup>
. In your code, you’re defininguseTemplateRef('container')
inside theinitThree
function, so it’s not accessible in theonMounted
hook since it’s outside the function’s scope. To fix this, you just need to moveconst container = useTemplateRef('container')
outside ofinitThree
and keep it at the top level of<script setup>
. That way, bothinitThree
andonMounted
can access it. Also, since you’re using Vue 3.5+,useTemplateRef
is the right choice overref
for template refs. Just make sure to checkcontainer.value
inonMounted
before using it to avoid null errors. Once you fix the scope, everything should work fine!