cannot access ref value inside v-if after mount
Vue version
"vue": "3.2.45"
Link to minimal reproduction
https://codesandbox.io/s/inspiring-brook-228g8g?file=/src/components/HelloWorld.vue
Steps to reproduce
When I want to access the value of a DOM ref inside a v-if
, when v-if=true
after onMounted
, I get null
.
If v-if=true
before onMounted
I can access the value.
See the console output of the codesandbox: https://codesandbox.io/s/inspiring-brook-228g8g?file=/src/components/HelloWorld.vue
<template>
<div class="hello">
<p v-if="showText1" ref="text1">TEXT1</p>
<p v-if="showText2" ref="text2">TEXT2</p>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue";
const showText1 = ref(true);
const showText2 = ref(false);
const text1 = ref(null);
const text2 = ref(null);
onMounted(() => {
// v-if is `true` before onMounted()
console.log("text1 ref", text1);
console.log("text1 ref.value", text1.value);
// v-if is set to `true` after onMounted()
showText2.value = true;
console.log("text2 ref", text2);
console.log("text2 ref.value", text2.value);
});
</script>
What is expected?
I can access the ref value when v-if=true
after onMounted
What is actually happening?
When I want to access the value of a DOM ref inside a v-if
, when v-if=true
after onMounted
, I get null
.
If v-if=true
before onMounted
I can access the value.
System Info
No response
Any additional comments?
Screenshot here https://imgur.com/a/FP4xZHd
Grrrr, seems I need to wait for nextTick(). This SO answer helped https://stackoverflow.com/questions/49031373/ref-array-inside-refs-undefine-inside-mounted