I have to display an array of objects in the DOM by using map method. Each item has a @click event listener where I want to highlight it with a CSS class 'hover'. The desired functionality is to mimic a menu system where only the clicked item should be highlighted, not all items at once.
Currently, all items are getting highlighted when clicked which is not the intended behavior. I've used console.log to track the clicked item but haven't been able to figure out how to highlight only that specific item instead of all items on the list.
<template>
<div>
<div>
<h1>Dragonball</h1>
</div>
<div>
<ul>
<li v-for="(dragonBallFighters, index) of dragonBallFighter" @click="toggleClass(dragonBallFighters.id)" :key=dragonBallFighters.id :class="{hover: active}">
<div class="dragonball-container">
<div class="dragonball-stats">
<h1>{{index}}, {{dragonBallFighters.name}}</h1>
<p>{{dragonBallFighters.race}}</p>
<p>{{dragonBallFighters.specialAttack}}</p>
</div>
<div class="dragonball-image">
<img :src="dragonBallFighters.img" :alt="dragonBallFighters.name" />
</div>
</div>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
active: false,
dragonBallFighter: [
// List of Dragon Ball fighters
]
};
},
methods: {
toggleClass(id) {
console.log('Clicked ' + id);
const currentState = this.active;
this.active = !currentState;
// this.selectedItemIndex = id;
if (this.selectedItemIndex === id) {
this.active === true;
} else if (this.selectedItemIndex === !id) {
this.active === false;
}
}
}
};
</script>
<style lang="scss" scoped>
.dragonball-container {
cursor: pointer;
display: grid;
padding: 20px;
grid-template-columns: 1fr 1fr;
//background: #666;
border: 2px solid #666;
grid-gap: 20px;
margin-bottom: 20px;
border-radius: 10px;
-webkit-box-shadow: 10px 10px 5px 0px rgba(240, 240, 240, 1);
-moz-box-shadow: 10px 10px 5px 0px rgba(240, 240, 240, 1);
box-shadow: 10px 10px 5px 0px rgba(240, 240, 240, 1);
}
.dragonball-image img {
display: grid;
justify-content: center;
align-items: center;
width: 100%;
max-width: 300px;
border-radius: 100%;
}
ul li {
list-style: none;
}
.hover {
background: rgb(244, 244, 244);
border-radius: 10px;
}
</style>