skip to Main Content

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?

2

Answers


  1. You forget to set the onceMounted = true;

    Before:

    onMounted(() => {
        onceMounted = false
        console.log(onceMounted)
      });
    

    After:

    onMounted(() => {
        onceMounted = true
        console.log(onceMounted)
      });
    
    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search