javascriptvue.js

Vue - v-if not updating with onMounted


I'm simply trying to make a div only appear once a variable changes from false to true and I'm telling it to change the value once the component is mounted. However the v-if which is supposed to be looking for that change is not working to create the div.

<script setup>
  import { onMounted } from 'vue'

  let onceMounted = false
  
  onMounted(() => {
    onceMounted = true
    console.log(onceMounted)
  });
<div>
  Hello
  <div v-if="onceMounted === true">
    World
  </div>
</div>

The console log confirms it changing fine, just the v-if isn't updating. I've checked using v-show after checking out other questions on here like this one. I'm guessing there's something I'm just missing?


Solution

  • onceMounted should be reactive using ref, then use .value to mutate it :

    <script setup>
      import { onMounted, ref } from 'vue'
    
      const onceMounted = ref(false)
      
      onMounted(() => {
        onceMounted.value = true
        console.log(onceMounted.value)
      });
    </script>
    <div>
      Hello
      <div v-if="onceMounted"><!-- no need for .value in template -->
        World
      </div>
    </div>