Search code examples
vue.jsanimationv-for

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


Using the v-for loop, I want to show the elements of the array I looped at certain intervals. For example, the first element of the array I looped should be displayed after 100ms, the second element 200ms, and the third element 300ms later. How can I solve this problem?


Solution

  • 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>