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

Error: Discord.js was unable to access the 'id' property because it was undefined

I need help with my ticket system project where I am trying to create a channel and send an embed in that channel. However, when I run the code, I encounter the error message TypeError Cannot read property 'id' of undefined. Here is the snippet ...

What precautions should I take when setting up my login routes to ensure security?

I am working on developing a login and registration system for a website project, but I'm unsure about the best way to safely implement the routes/logic for it. Currently, in my client-side code, I make fetch requests to either the login or register r ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

Encountered an issue with launching Chrome in Puppeteer for Node.js

My code was uploaded to EC2 AWS, but unfortunately it is not working properly after the upload. Interestingly, it runs correctly on localhost. Despite trying various solutions, I am still facing this issue. Any suggestions on the correct approach to resolv ...

Bug detected in the brfs plugin for browserify

I'm currently working on a project where I need to consolidate all the .html template files into a single bundle.js file by reading the content from each .html file. In my main.js, I have written the following code: var fs = require('fs'); ...

Tips on handling jsonp responses in CakePHP without using the .json extension

When working with CakePHP, the framework determines the data type to return by either checking for the presence of the .json extension in the URL or examining the Accepts HTTP header. It becomes a bit trickier when dealing with JSONP, as it doesn't a ...

Trigger a Nuxt/Vuejs event upon completion of rendering all page components

Is there a way to trigger an event after all components on a page have finished rendering? I've attempted using the page mounted event, but it only fires the first time. I need an event to be triggered each time the route changes on the client side an ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

Having difficulties redirecting with the button's onclick function

I'm struggling to redirect users to another page using a button (assuming the hostname is localhost:8000) $('#getFruit').attr('onclick', window.location.host + '/getFruit/banana') <script src="https://cdnjs.cloudfl ...

Steps for Adding a class or Id to an Ext.Msg.alert box

Is there a way to customize the style of a specific Ext alert box without affecting all alert boxes? Can someone please explain how to assign a class or ID to an Ext.Msg.alert box? Ext.Msg.alert('Status', 'Changes saved successfully.' ...

How can you retrieve the X.509 Certificate from a P12 file using Node JS?

I obtained a p12 file that contains an X.509 Certificate. To handle this file, I am utilizing the forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'b ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...

Discover innovative ways to define reactive attributes within Vue.js

I am working on a parent component that passes a config object as props to its child component. My goal is to make certain entries in this config object reactive, such as: created() { this.config.page = this.config.page || 1 } Once I do this, any c ...

The functionality of Skrollr on mobile is currently not working properly due to the inability to prevent default actions

Encountering the following error on all chromium browsers while using the Skrollr library and accessing the website through mobile: "[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See < ...

What is the process for utilizing Sass in Vue CLI rather than node-sass (which is the default for sass-loader)?

I found a solution, but it's specifically for Nuxt.js and I'm using the Vue CLI. Is there any way to use dart sass instead of node-sass (default for sass-loader) in Nuxt.js? While the Vue CLI official documentation displays an example utilizing ...

Error with setting innerHTML property of a null nested div

This issue arises when the element is referenced before the DOM has completely loaded. To combat this, I have ensured that the necessary script runs only after the window has finished loading. Interestingly, if the getElementById() call is for a standalon ...

How to extract a value from a span input textbox using Vue?

I just started using Vue and I'm attempting to create an auto-growing input. I've realized that it's not possible to create a real <input> element that adjusts its size based on its content and allows for value modifications using v-mo ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Customizing the font color and size of the MUI DatePicker default textfield is not supported

I'm encountering an issue with the MUI DatePicker as I am unable to customize the font color and font size of the date. Below is my code: const DateSettings = () => { const [value, setValue] = React.useState<Date | null>(); const handleC ...