1

I am new in Vue.js. I need to display an array of elements. Each element contains information about the user, including the color in which I need to display div.

<template>
    <ul>
        <li v-for="(result, index) of results" :key="index">
            <div v-bind:style="{ color: result.color }">
                user info
            </div>  
        </li>
    </ul>
</template>

When adding a new element to the beginning of the array, the list of divs seems to be cached. For example, i have some divs:

<li>
    <div v-bind:style="{ color: user1.color }">
        User1 info
    </div>  
</li>
<li>
    <div v-bind:style="{ color: user2.color }">
        User2 info
    </div>  
</li>

And then i add new element:

    <li>
        <div v-bind:style="{ color: user1.color }">
            User3 info
        </div>  
    </li>
    <li>
        <div v-bind:style="{ color: user1.color }">
            User1 info
        </div>  
    </li>
    <li>
        <div v-bind:style="{ color: user2.color }">
            User2 info
        </div>  
    </li>

That is, the style of new item remains from the previous user. When you reload the page, the styles are displayed normally. This only happens on large arrays.

Data is added to the array this way:

vm.results.unshift.apply(vm.results, dataResult);

Where could there be a mistake?

  • @AlexH, vm.results.unshift.apply(vm.results, dataResult) is inside of setInterval function. – Daria Korosteleva Jun 10 '20 at 19:55
  • A solution I've seen is assigning `this` to a variable before the `setInterval`, then using that variable in place of `this` inside the `setInterval`. Something like this: `var that = this; setInterval(() => {... that ...}, interval)`. – AlexH Jun 10 '20 at 19:59
  • AlexH, it is done this way. let vm = this; setInterval(async function() { vm.results.unshift.apply(vm.results, dataResult); }, 5000); – Daria Korosteleva Jun 10 '20 at 20:07