Search code examples
javascriptloopsvue.jsvuexv-for

Loop through a list of names and loop through a list of colors and bind the background color style to one of those names


Am looping through an array of colors in my store from a Vue component, then am also looping through an array of names from same store and displaying them in a div in my component. I would like to bind each div with the name to one of the colors, My code looks like

<div  
           class="names"
            v-for="user in getUsers" 
            :key="user.id">
            <div
                id='user'
                v-for="color in getColor"
                :key="color.id"
                :style="{backgroundColor:color}"
                >{{user.name[0]}}
            </div>
        </div>

The problem is Its showing one name for all five colors I have For instance name james is shown in all five colors, then name susan in all five colors. I am also pulling the store data using a computed property.

computed: mapState({
    getUsers: state => state.users,
    getColor: state => state.colors })       

Solution

  • You need one loop and use its index to get the details of the other entry based on the colors length and modulo % :

         <div
            class="names"
            v-for="(user,index) in getUsers" 
            :key="user.id">
            <div
                id='user'
                :style="{getColors[index%getColors.length]}" >
                  {{user.name}}
            </div>
        </div>