Daria Korosteleva
Daria Korosteleva

Reputation: 171

Vue.js styles do not change when adding a new element to an array displayed in v-for

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?

Upvotes: 1

Views: 496

Answers (1)

Daria Korosteleva
Daria Korosteleva

Reputation: 171

The problem was that color may be empty. In that case div contains an empty style and when adding a new element, it is assigned the style of the previous element.

To solve the problem it was necessary to add a default color:

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

Upvotes: 1

Related Questions