Skip to content
Advertisement

Vue – Loop through an array of objects, and highlight the selected item on click

I have an array of objects which holds data, which I output to the DOM using map. Each item in the list, has a @click event listener. When you click on one of the items, I want it to be highlighted by way of adding a css class, for example ‘hover’. So basically it should work like a menu system. When you click on an item, that item is highlighted and the others should not be highlighted and vice versa.

The way i have it set up right now, all of the items in the list get highlighted, which is not the logic i’m trying to do. I have used console.log, to display which item has been clicked. However, I still have not figured out, how to make that selected item, the one thats highlighted instead of the whole list?

JavaScript

Advertisement

Answer

My prefered way to do this is by adding a new key to each of the fighters and using that key in the v-for. The only thing needed in the markup is to change the :class value to be the active key in from the fighters in the v-for loop.

JavaScript

Then for the Javascript, we use Vue.set() to tell the dom that we added a key that is not in the original object that v-for is aware of. This makes vue correctly update the dom when we change the fighter’s ‘activeness’.

JavaScript

Live example

The way I toggle the active class is simply by doing !fighter.active. This will be translated to not {boolean} ~ If the fighter.active is true then not true will equivalent in false. If it is false, not false will equivalent to true

Btw; I would suggest you to rename the object of fighters to dragonBallFighters. This way, the v-for makes more sense == <v-for="fighter in dragonBallFighters" One could translate that to

for each fighter in the dragonBallFighters object.

Per now, you are indirectly saying

for each dragonBallFighters in the dragonBallFighter object

witch doesn’t float the same on the tongue 😉

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement