简体   繁体   中英

Vue.js, Interval timer on v-for

So I'm loading in some data and I'm rendering it to the DOM with a v-for loop in my template. Now I would like to make the data appear at an interval. ie; a new message shows up every second.

The only way I could think of is to hide all the messages with css and make them (re)appear by unhiding them one at a time. However, I don't think this is the right way to go about this.

So if any of you has a suggestion for how I should go about this, would be great!

There are multiple ways to handle this. You could use two arrays. One to hold the data you want to show and the other to show it. Then put an interval function in the created function that will transfer the items from the hold array to the show array. Like so:

 new Vue({ el: "#app", data: { todos: [ ], soonTodo: [ { text: "Learn JavaScript", done: false }, { text: "Learn Vue", done: false }, { text: "Play around in JSFiddle", done: true }, { text: "Build something awesome", done: true } ], interval: null, }, methods: { toggle: function(todo){ todo.done = !todo.done } }, created() { this.interval = setInterval(() => { if (this.soonTodo.length) { this.todos.push(this.soonTodo.shift()); } else { clearInterval(this.interval); } }, 1000) } })
 body { background: #20262E; padding: 20px; font-family: Helvetica; } #app { background: #fff; border-radius: 4px; padding: 20px; transition: all 0.2s; } li { margin: 8px 0; } h2 { font-weight: bold; margin-bottom: 15px; } del { color: rgba(0, 0, 0, 0.3); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script> <div id="app"> <h2>Todos:</h2> <ol> <li v-for="todo in todos"> <label> <input type="checkbox" v-on:change="toggle(todo)" v-bind:checked="todo.done"> <del v-if="todo.done"> {{ todo.text }} </del> <span v-else> {{ todo.text }} </span> </label> </li> </ol> </div>

Another way, if you want to alter your data structure, is to have a show property on your data that v-show could bind to. Then your interval function would just run through the array each time setting that property to true until each item is showing.

// JS 
{ text: "Learn JavaScript", done: false, show: false }

// HTML
<li v-for="todo in todos" v-show="todo.show">
  <label>
    <input type="checkbox"
      v-on:change="toggle(todo)"
      v-bind:checked="todo.done">

    <del v-if="todo.done">
      {{ todo.text }}
    </del>
    <span v-else>
      {{ todo.text }}
    </span>
  </label>
</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM