Search code examples
vuejs3vue3-openlayers

Why is ref in onMounted null in vue3?


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>

Solution

  • ref should be written at the top level

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