skip to Main Content

I’m trying to make a preloader as a v-if component on the page for 2 second and than toggle view to another block. But I can’t get hoe to write it correctly. Also do I need to add an endSettimeout method ?

<script setup>
  let loading = ref(false)

  const showModal = () => {
  loading = true
  const load = setTimeout(() => {
    loading = true
    modalVisible.value = true
  }, 2000)
  loading = false
  
}
</script>

<template>
  <div>
    <div class="preloader" v-if="loading == true"></div>
    <div class="wrapper">
      <Modal v-model="modalVisible" v-if="modalVisible" />
      <div class="form__container" v-else>
  </div>  
</template>

2

Answers


  1. You must also start loading – e.g. when the component is loaded (with onMounted)

    <script setup>
    import {onMounted, ref} from 'vue'
    
    let loading = ref(false)
    let modalVisible = ref(false) // init modalVisible
    
    const showModal = () => {
        loading.value = true
    
        setTimeout(() => {
            loading.value = false
            modalVisible.value = true
        }, 2000)
    }
    // start loading here
    onMounted(async () => {
        showModal()
    })
    </script>
    
    Login or Signup to reply.
  2. In your setTimeout, you should set loading to false after the timeout, not before it and you need to initialize modalVisible as a reactive variable using ref().

    <script setup>
      import { ref } from 'vue';
    
      let loading = ref(false);
      let modalVisible = ref(false);
    
      const showModal = () => {
        loading.value = true;
    
        setTimeout(() => {
          loading.value = false;
          modalVisible.value = true;
        }, 2000);
      };
    </script>
    
    <template>
      <div>
        <div class="preloader" v-if="loading"></div>
        <div class="wrapper">
          <Modal v-model="modalVisible" v-if="modalVisible" />
          <div class="form__container" v-else>
            <!-- Your form content goes here -->
          </div>
        </div>
      </div>
    </template>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search