A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected.

I attempted binding the class to a variable, but this resulted in all items being impacted simultaneously.

<template>
  <ul>
    <li class="item" v-for="item in items" @mouseenter="showInfoBar()" @mouseleave="hideInfoBar()">
        <span class="infobar" :class="{ show : infoBar }"> </span>
    </li>
  </ul>
</template>

<script>
export default {
  name: 'ItemsList',
  props: ['items'],
  data()  {
    return {
      infoBar: false
    }
  },
  methods: {
    showInfoBar() {
      this.infoBar = true
    },
    hideInfoBar() {
      this.infoBar = false
    }
  }
}
</script>

Answer №1

Here is an alternative approach you could take:

<template>
  <ul>
    <li class="item" v-for="(item, index) in items" :key="index" @mouseenter="infoBar = index" @mouseleave="infoBar = null">
        <span class="infobar" :class="{ show : infoBar == index }"> </span>
    </li>
  </ul>
</template>
Then, for your data property:
data()  {
    return {
      infoBar: null
    }
},

Answer №2

The issue here lies in the fact that the variable infoBar is being used to represent the state of all info bars collectively, instead of each info bar individually.

To resolve this, you can transform infoBar into an array where each element corresponds to the state of the info bar at a specific index.

<template>
  <ul>
    <li class="item" v-for="(item, index) in items" @mouseenter="showInfoBar(index)" @mouseleave="hideInfoBar(index)">
        <span class="infobar" :class="{ show : infoBar[index] }"> </span>
    </li>
  </ul>
</template>

<script>
export default {
  name: 'ItemsList',
  props: ['items'],
  data()  {
    return {
      infoBar: []
    }
  },
  mounted: function() {
    for(var i = 0; i < this.items.length; i++) {
      this.infoBar.push(false);
    }
  },
  methods: {
    showInfoBar(index) {
      this.infoBar[index] = true;
    },
    hideInfoBar(index) {
      this.infoBar[index] = false;
    }
  }
}
</script>

Answer №3

In my opinion, it would be more efficient to handle this not as an array but as individual components. It is best practice to let each component manage its own state rather than managing the state of a group of "components" in an array. Taking inspiration from React, you can define ItemsList and Item as separate components with each Item having its own state. Let me know if you agree with this approach. Best of luck.

Revised Thoughts After Reviewing the Code

I also suggest that after refactoring your code, instead of handling state changes in two separate methods, you should create a single toggleMethod() where you toggle the current state value logically.

This approach is preferable:

function toggleState() {
    this.someState = !this.someState;
}

Over this method:

function showState() {
    this.someState = true;
}
function hideState() {
    this.someState = false;
}

Best of luck!

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 steps should I take if the slackbot is properly functioning after being invited to the channel?

Using an OAuth2 token I am looking to automate the process of sending data from Google Sheets via Slackbot. Even though I have set up tokens and connections, I find that I still need to manually input the channel id into my script. In order to streamline ...

Broaden material-ui component functionality with forwardRef and typescript

To enhance a material-ui component with typescript, I have the javascript code provided in this link. import Button from "@material-ui/core/Button"; const RegularButton = React.forwardRef((props, ref) => { return ( <B ...

What is the best way to transfer data between my express middleware functions?

Hello, I am new to working with Javascript/Node/Express and currently trying to interact with the Facebook Graph API. Below is an Express middleware function that I have set up: My goal is to follow these steps: Acquire a user authentication token fro ...

A valid path is required in the form of a string when working with the HTTP module in Node.js

Currently, I'm working on an update checker that doesn't involve downloading the update. My main goal is to compare the version in the package.json file on GitHub with the one in my Electron app. However, when using this code, I encountered a "p ...

Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one: var array= [ [1,"dataA","dataB","dataC","dataD"...], [2,"dataA","dataB","dataC","dataD"...], [3,"dataA","dataB","dataC","dataD"...], [4,"dataA","dataB","dataC","dataD"...]... ...

Identifying Inactivity in Cordova Android Applications

Hey there! So, I've created a flashlight/torch app that can be found at the following link: https://github.com/Skelware/Fancy-Flashlight. This app utilizes a Cordova plugin available here: https://github.com/Skelware/Cordova-Flashlight. For now, my m ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

Is it possible to utilize a keyboard listener to activate a tooltip upon being invoked?

I've created a basic pie chart that shows a tooltip when you click on a pie wedge. Now, I want to achieve the SAME functionality, but for div elements located OUTSIDE of the pie chart. Situation: A user focusing on the 'Cat 1' div and ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

How can I efficiently display three items per click when tapping into jQuery data?

Here is the code that I have been working on: jQuery(document).ready(function( $ ) { var $container = $('#homegrid').masonry({ isAnimated: true, itemSelector: '.home-blocks', columnWidth: '.grid-sizer ...

experimenting with adding fresh choices to dropdown menu using ajax and jquery

When attempting to load a list of locations through ajax/jQuery, I encounter an issue. After typing a letter into the input field, the first response is displayed but subsequent responses are simply appended to it. I have tried using .html('') an ...

Exploring the versatility of HTTP actions in Express: Using GET and

Currently, I am setting up a server through express. While everything is running smoothly with my project, I have a small query that is not related to the project itself. My confusion lies in the requirement to use the GET method when, in my opinion, usi ...

Make the table in a bootstrap design appear with a border when you hover over a cell using the table

Looking for a solution to make the border work as expected when hovering over each td in a table like this example: https://jsfiddle.net/nmw82od1/ Here is the CSS code: .table1 td:hover { border: 1px solid black; } .table2 td:hover { border: 1px do ...

the status of the XMLHttpRequest Object within the realm of jQuery AJAX

When using traditional JavaScript AJAX, we monitor the readystate property to determine the status: 0 - The request is not initialized 1- The request has been set up 2 - The request has been sent 3 - The request is in process 4 - The request is compl ...

What is causing the initial activation of the <button> within a form?

Within my <form>, I have included 2 submit buttons. The first button looks like this: <button class="regular" id="geocodesubmit" style="height:40px;">Set Location</button> The second button looks like this: <button type="submit" ...

Ensure that grid rows occupy the least amount of space possible

I'm relatively new to grid layout and I've encountered a challenge that has me stuck. Here's what I have so far: codepen And this is the relevant part of the grid: grid-template: 'img date' 'img head' 'img s ...

Experimenting with Selenium to automate processes involving dynamic class attributes

My issue involves a Button class = "searchbar__SearchButton-sc-1546roh-3 searchbar__CancelButton-sc-1546roh-4 glEceZ" I am attempting to locate this element in the browser using return browser.element('button[class^="searchbar__CancelButton-"]&ap ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...