Home > Net >  How can I render elements in v-for loop with different times?
How can I render elements in v-for loop with different times?

Time:04-02

I want to render elements at different times to use animation with the v-for loop. For this, I tried to set a value of the loop elements as false at the beginning and convert it to true after 100ms, 200ms, and 300ms with the setTimeout function, but I failed. How can I solve this problem?

CodePudding user response:

You can achieve that via using setTimeout and pass the timeout dynamically based on the index.

Working Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      list: [{
        isFlag: false
      }, {
        isFlag: false
      }, {
        isFlag: false
      }]
    }
  },
  mounted() {
    this.list.forEach((obj, index) => {
      setTimeout(() => {
         obj.isFlag = true
      }, 100 * (index   1));
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="(item, index) in list" :key="index">
      {{item.isFlag}}
    </li>
  </ul>
</div>

CodePudding user response:

Well, I think I haven't fully explained the question. Actually what I wanted was a conditional notation. I thought of using v-if for this but I didn't want to use it with v-for. I have reached the solution by adding the elements that I want to show to the array at regular intervals. I found a way to accomplish what I want I hope this is helpful.

const app = new Vue({
  el: '#app',
  data() {
    return {
      itemArr: []
    }
  },
  mounted() {
    let item1 = {
      title: "Item1"
     };
    let item2 = {
      title: "Item2"
     };
    let item3 = {
      title: "Item3"
     }
    
    setTimeout(()=>{
      this.itemArr.push(item1)
    },100)
    
    setTimeout(()=>{
      this.itemArr.push(item2)
    },200)
    
    setTimeout(()=>{
      this.itemArr.push(item3)
    },300)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
  <div >
    <div  v-for="item in itemArr" :key="item.title">
      {{item.title}}
    </div>
  </div>
</div>

<style>

.main{
  display:flex;
  gap:10px;
}

@-webkit-keyframes fade-in-fwd {
  0% {
    -webkit-transform: translateZ(-80px);
            transform: translateZ(-80px);
    opacity: 0;
  }
  100% {
    -webkit-transform: translateZ(0);
            transform: translateZ(0);
    opacity: 1;
  }
}
@keyframes fade-in-fwd {
  0% {
    -webkit-transform: translateZ(-80px);
            transform: translateZ(-80px);
    opacity: 0;
  }
  100% {
    -webkit-transform: translateZ(0);
            transform: translateZ(0);
    opacity: 1;
  }
}

.fade-in-fwd {
    -webkit-animation: fade-in-fwd 0.6s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
            animation: fade-in-fwd 0.6s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
}

</style>

  • Related