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?

6
  • Perhaps use this instead of vm? Commented Jun 10, 2020 at 19:49
  • Or perhaps see this question and try one of those methods and see if they make the array reactive. Commented Jun 10, 2020 at 19:52
  • I think you should use in instead of of in <li v-for="(result, index) of results" :key="index"> Commented Jun 10, 2020 at 19:53
  • @AlexH, vm.results.unshift.apply(vm.results, dataResult) is inside of setInterval function. Commented Jun 10, 2020 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). Commented Jun 10, 2020 at 19:59

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Good, it's an interesting issue thanks for sharing the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.