Incorporate v-if to target a particular item within a v-for loop

On my Vue page, I have the following HTML code snippet:

    <div v-for="profile in lab.profiles" v-if="edit || profile.active" class="lab-tests-row-div" @mouseover="">
        <div class="clickBox" :class="['clickBox-' + lab.id + '-' + profile.id]" @click="openInfoPopup"></div>
        <p class="lab-tests-row test-info-row" v-bind:class="{'active': profile.active}">
            <span v-bind:class="{'opacity50':!profile.active}">{{profile.name}}</span> 
            <i v-if="edit" class="fa fa-minus pull-right removeTestIcon" aria-hidden="true" @click="toggleProfile(lab.id, profile.id)"></i>
            <span class="pull-right" v-bind:class="{'opacity50':!profile.active}">{{profile.code}}</span>
        </p>
    </div>

I am facing an issue where I want to display the 'clickBox' element only when the user hovers over a specific row. However, if I use a v-if with a boolean and change it on mouseover, all rows show the clickBox since they are part of a v-for loop. How can I ensure that only the div in the particular row being hovered over is shown?

Answer №1

When using the v-for directive, you have access to the index of each element with v-for="(profile, index)

You can utilize this index to apply specific styles in your template.

For instance:

new Vue({
  el: '#app',
  data: {
    selected : 0
  }
})
.selectedClass {
  background: lightblue
}

.hoverClass:hover {
  background: lightcoral
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<main id="app">
  <div v-for="(elem, index) in 4">
    <p class="hoverClass" :class="{'selectedClass': selected === index}" @click="selected = index" >{{elem}}</p>
  </div>
</main>
https://stackoverflow.com/posts/54025706/edit#

Update

Combining class="..." with Vue binding :class="..." is a valid approach.

Additional Edit

If dealing with nested v-for, consider assigning distinct names to the indexes.

new Vue({
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<main id="app">
    <div v-for="(item, i) in 2">
       <div v-for="(elem, j) in 3">
        v-for item {{ i }} v-for elem {{ j }}
       </div>
    </div>
</main>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Check if a user is currently on the identical URL using PHP and JavaScript

In my Laravel and AngularJS project, I have a functionality where users can view and edit a report. I'm looking to add a feature that will prevent multiple users from editing the report at the same time - essentially locking it while one user is makin ...

Achieve a full page layout with content and attach the footer to the bottom using flexbox in Tailwindcss and Nextjs

How can I use flex-grow to make the body section fill the screen and keep the nav fixed at the bottom? I'm having trouble figuring out which elements to apply these properties to. Can anyone provide guidance on which element should have these styles? ...

Display localization keys in Vue using i18n

Are there any ways to display the keys using localization? I came across a solution in the documentation which suggests creating decision maps for fallbackLocale. My approach was to define a decision for default -> en and a decision for 'not-a-lan ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one. Here's an example of what I'm looking ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

Developing distinct state values for assigned objects

I developed a star rating component using Material UI components that is based on a mapped object. However, I am facing an issue where all the star ratings show the same value when clicked. How can I ensure that each star section displays its own value bas ...

Issues with setSelectionRange functionality in JavaScript unit tests leading to unexpected behavior

Currently, I am utilizing the qunit framework to perform unit testing on interactions within an HTML element that has been dynamically created using jquery (specifically, var $textarea = $('')) in Chrome. Below is the code snippet I am employing ...

What is the best way to include a new array at the beginning of a lexicographically sorted array?

After lexicographically sorting an array, I am trying to figure out how to add values from another array "cityOfTheMoscow" first and then maintain the lexigraphical order. However, while using the code snippet below: result.unshift(...self.cityOfTheMoscow ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

The map failed to display any information

<div> {!props.isLoading && <div> {normalizedData.map((outerObj,index) => { { <p className="space_name"> {outerObj.space_name} </p> ...

The submission of the form using AJAX is currently experiencing issues

My current issue involves ajax not functioning as intended. I have a form that is being submitted through ajax to my php file for the purpose of updating my database. The database update is successful, but there seems to be a problem with the ajax function ...

Creating complex concave shapes using Three.js from a point cloud

Currently facing a challenge in dynamically creating shapes in three.js from a point cloud. While ConvexGeometry works well for convex shapes, it becomes complex when dealing with concave shapes. The process involves drawing a line on the 2D plane (red li ...

The Ajax Form disappears from the page

After racking my brain for a while, I've come to the conclusion that it's time to seek some assistance. I have work tomorrow and I don't want to spend all night on this. The issue lies in my form which is located inside a modal, here is my ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...

Foreign keys in a one-to-many relationship with Sequelize.js

I am in the process of developing a survey application using Node.js/Express and MySQL incorporating Sequelize.js ORM. However, I am encountering difficulties while establishing the relationship between the two models. My goal is to have the Questions&apo ...

JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object. var productValues = 0; var cart = function(){ this. ...

Change a reactive variable based on an event

I am currently working on a file upload feature in my application. Template.uploadFile.events({ 'change .set-file': function ( event, template ) { var file = event.currentTarget.files[0]; [...] } }); My goal is to read each row fro ...