When faced with such scenarios, it becomes necessary to keep track of the id of the currently active element within the data of the parent component. This can be achieved by storing the id when a row is selected.
Parent
<template>
<div class="menu">
<MenuItem
v-for="row in rows"
:active-id="activeId"
:key="row.id"
@select="handleSelect"
/>
</div>
</template>
<script>
import MenuItem from "./MenuItem";
export default {
name: "TheMenu",
components: {
MenuItem,
},
data() {
return {
activeId: null,
rows: [
{
id: 1,
label: "First",
},
{
id: 2,
label: "Second",
},
{
id: 3,
label: "Third",
},
],
};
},
methods: {
handleSelect(id) {
this.activeId = id;
},
},
};
</script>
Child
<template>
<div
class="menu-item"
:class="{
'menu-item_active': activeId === row.id,
}"
@click="handleSelect"
>
{{ row.label }}
</div>
</template>
<script>
export default {
name: "MenuItem",
props: {
row: {
type: Object,
required: true,
},
activeId: {
type: Number,
required: true,
},
},
methods: {
handleSelect() {
this.$emit("select", this.row.id);
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.menu-item {
/* your styles */
display: flex;
width: 100%;
}
.menu-item_active {
background-color: red;
}
</style>