Home > Back-end >  Autohide an element in Vue.js after 2 seconds
Autohide an element in Vue.js after 2 seconds

Time:03-02

i want

<div >
<div ><div ></div></div>
</div>

to be hidden after 2 seconds, any way i can do that?

CodePudding user response:

You could add a property in the data object and use v-show directive to determine whether the element should be visible or not. If the boolean is false the element is hidden, if true the element is visible.

Method Created called synchronously after the instance is created.

 <template>
        <div>
            <h1 v-show="elementVisible" > HELLO </h1>
        </div>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    elementVisible: true
                }
            },
    
            created() {
                setTimeout(() => this.elementVisible = false, 2000)
            }
        }
    </script>

CodePudding user response:

<template>
  <!-- binding style -->
  <div  :style="{visibility: showLoader ? 'visible' : 'hidden' }"

  <!-- or use v-show directive to show | hide element -->
  <div  v-if="showLoader">
    <div ><div ></div></div>
  </div>
</template>

<script>
  data() {
    showLoader: true,
  },
  mounted() {
    this.hideLoader()
  },
  methods: {
    hideLoader() {
      // using setTimeout to programmatically hide loader
      setTimeout(() => {
        this.showLoader = false
      }, 2000)
    }
  }
</script>

CodePudding user response:

You can write the logic to hide the loader in mounted() hook. Vue calls the mounted() hook when your component is added to the DOM.

Working Demo :

new Vue({
  el: '#app',
  data: {
    isLoaderVisible: true,
  },
  mounted() {
    setTimeout(() => {
      this.isLoaderVisible = false
    }, 2000)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div  v-if="isLoaderVisible">
    <div >
      <div >
        Loading...
      </div></div>
  </div>
</div>

  • Related