Why is ref in onMounted null in vue3?

1.3k views Asked by At

It is normal to write it in setup, but it prints a null in onMounted; What is the reason? Isn't onMounted between the two executed later, and the dom has been loaded, why can it be obtained in the setup instead?

<script setup lang="ts">
   const refDom = ref<any>(null);
   console.log(1, refDom.value); //Write this to get
</script>
<script setup lang="ts">
onMounted(()=>{
  const refDom = ref<any>(null);
  console.log(2, refDom.value); // print out here is null
})
</script>
1

There are 1 answers

0
Kan Robert On BEST ANSWER

ref should be written at the top level

<script setup lang="ts">
const refDom = ref<any>(null); 
onMounted(()=>{
   console.log(2, refDom.value);
})
</script>