简体   繁体   中英

Vue v-for doesn't update directly

SOLVED: My bad.The problem is in my code logic, the tempLatest array is always empty so the array that contains the card never been updated. btw, thank you for all your answers

I want to create a program that show a collection of card. That collection will be updated every 15 seconds. But here comes the problem, the v-for doesn't update directly when a new card added to the list but when the page is refreshed it shows the proper output.

here is my code

<PersonCard v-for="item in latest" v-bind:key="item.id" :attendeeName="item.name" :image="item.picture" :department="item.department"/>
data() {
        return {
            latest: [],
            imgArr: [],
            notReady: true,
        }
    }
created() {
        console.log(this.site, this.sinceTime)
        this.fetchRecognizedFace();
        this.timer = setInterval(this.fetchRecognizedFace, 15000);
    }
// update this.latest
for (var j = 0; j < tempLatest.length; j++) {
    this.latest.unshift(tempLatest[j]);
}

use the vue forceUpdate method ways to rerender component

import Vue from 'vue';
Vue.forceUpdate();

after you update the latest variable, call this one

this.$forceUpdate();

There are limitations with how arrays can be re-active in Vue (See: https://v2.vuejs.org/v2/guide/list.html#Caveats ).

With this in mind, when you do your update, do it like so:

for (var j = 0; j < tempLatest.length; j++) {
    this.$set(this.latest, j, tempLatest[j]);
}

Note: I've not tested this with your code so you might need to play around a little as you're currently looping the temp list and the indexes might not match but $set is the way to go. You might also try:

this.$set(this, 'latest', tempLatest)

instead of looping each item.

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