Hover over a particular element using a loop in Vue.js

Is there a way to change the price button to an Add to Cart button on mouseover, considering the true false data trigger for each item? How can we specify which item to target when hovering over the price section?

Below is the code snippet: template:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <div v-for='(item,index) in itemList' :key='index'  class="col-md-6 ">
            <img :src="require('../assets/img/'+item.itemImg)" class='itemImage6' alt="">
            <span class='itemSpan6'>{{item.title}}</span>
            <span class='itemSpanSecond6'>{{item.itemName}}</span>
            <div  @mouseenter='mouseEnter(index)' @mouseleave='mouseLeave(index)'>
             <span class='btn itemSpan' :id='item.productID' v-if='!add' > ${{item.itemValue}}</span>
            <span class='btn itemSapn' v-if='add' style='color:white;background:#b4a895;' ><i class="fas fa-plus"></i></span>
            </div>
            <div class="star_rating">
              <span  :id="item.productID+1" class='btn star' @click='fillstar(item.productID,1)'>&star;</span>
              <span  :id='item.productID+2' class='btn star' @click='fillstar(item.productID,2)'>&star;</span>
              <span  :id='item.productID+3' class='btn star' @click='fillstar(item.productID,3)'>&star;</span>
              <span  :id='item.productID+4' class='btn star' @click='fillstar(item.productID,4)'>&star;</span>
              <span  :id='item.productID+5' class='btn star' @click='fillstar(item.productID,5)'>&star;</span>
            </div> 
          </div>
</div>
</body>
</html>

methods:

   mouseEnter(id){
      this.itemList.map((item)=>{
        if(item.id == id){
          this.add=true;
        }
      });
    },
    mouseLeave(id){
      this.itemList.map((item)=>{
        if(item.id == id){
          this.add=false;
        }
      });
    }

Answer №1

In Vue, you can loop through items and store the id in a data variable. Here is an example that demonstrates this concept:

<div v-for="(item, index) in itemList">
  <button @mouseleave="action = null"
          @mouseover="action = item.id"
 >
    hover button
 </button>
 <span v-show="action === item.id">Add to cart</span>
</div>
data() {
  return {
    action: null
  }
}

Answer №2

To incorporate this functionality into your methods, simply follow these steps:

mouseEnter(id){
      this.itemList.map((item)=>{
        if(item.id == id){
          this.add = true;
          this.setValue[index] = item.itemValue; //additional line
        }
      });
    },

Don't forget to replicate the same process in mouseLeave(), and make sure to declare it within your data return as shown below:

data() {
  return {
    this.setValue: ""
  }
}

In your template, you can verify it using {{setValue[index]}}

This method should resolve your issue effectively!

Answer №3

What is the advantage of using JavaScript over CSS?

// Implementing functionality in your component
<a href="#" class="link">
  <span class='btn itemSpan btn-value' :id='item.productID'>${{item.itemValue}}</span>
  <span class='btn itemSapn btn-add' style='color:white;background:#b4a895;' ><i class="fas fa-plus"></i></span>
</a>

// Styling with CSS
.btn-add { display: none; }
a.link:hover .btn-add { display: block; }
a.link:hover .btn-value { display: none; }

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

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

What is the best method for securing my API key within the script.js file while utilizing dotenv?

My goal is to conceal my API key using dotenv. Interestingly, when I replace require('dotenv').config(); with my actual API key in the code as apiKey: process.env.API_KEY, it works fine despite not using process.env.API_KEY. I made sure to inst ...

The functionality of a radio button triggering a form submission to different pages is experiencing issues with Firefox

This piece of code is designed to submit a form when a radio button is clicked, and depending on which radio button is selected, the form action should change. While this code works fine in Chrome and Opera, it doesn't seem to function properly in Fir ...

New patch request received in Google Sheets, replacing the existing post request

I am transferring 12 cell values from a Google Sheet to a MongoDB database. The purpose behind this action is to merge the 12 cells, perform certain data transformations, and display the output on a frontend interface later on. Moreover, I'm faced wit ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

Exploring ways to create simulated content overflow using react-testing-library

I have integrated material-table with material ui to develop a spreadsheet application. One of the features I have added is setting a maximum width of 50px for cells. If the content in a cell exceeds this width, it will display an ellipsis at the end of ...

What is the best way to hide the input field when there are multiple parent classes present?

I am currently implementing dynamic fields with jQuery and everything is functioning correctly. The problem arises when I attempt to remove these fields. After searching on Google and browsing past questions on StackOverflow, I noticed that everyone seems ...

Troubleshooting Problem with Accordion Size in CSS

I am facing an issue with a dropdown menu that I have created. The dropdown has parent and child rows to display controls, but the width of the Accordion is not stretching as expected despite being set to 100%. Using Chrome and Edge developer tools, I insp ...

Tips for stopping the submission of a form

My current form includes ajax calls: <form method="post" action="?slt=Sbmt" onsubmit="return validateForm()" id="reportform" enctype="multipart/form-data"> <div id="evaluation1"> <h2>Rate Technical Skills</h2> <table class= ...

Tips on enhancing an array by separating values with vertical bars instead of commas

I am trying to store checked values in an array and separate them with vertical bars instead of commas. Is there a way to achieve this using the jQuery map .get() function? Any suggestions or links you can provide would be greatly appreciated. Thank you in ...

The "click" event is only effective for a single use

I am looking for a way to trigger the click event more than once in my project. I attempted using "live" but it didn't work as expected. There are 2 other similar scripts in this Django project. If you have any suggestions on improving this project, p ...

Is there a way to retrieve the id of a jQuery autocomplete input while inside the onItemSelect callback function?

I am currently utilizing the jquery autocomplete plugin created by pengoworks. You can find more information about it here: Within the function that is triggered when an entry is selected, I need to determine the identifier of the input element. This is i ...

How does the performance contrast between "skip if condition" and "immediately return"?

Do you know if there is a performance variance between these two functions? function x() { var x = false; if(x == true) { ... Numerous lines, like 1 million ... } } function y() { var x = false; if (x != true) { retu ...

Implement a transformation on the API endpoint's JSON data to prepare it for display in a React

I'm currently developing a React application and have created a component to display tabular data. The API endpoint I am calling returns data in the following format: { "bitcoin": { "usd": 48904, "usd_market_cap": 9252 ...

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

"Encountering a freeze in mobile Chrome while subscribing to streamCreated events using Opent

Currently, I am working on developing a webRTC chat using the opentok platform and vue.js. Everything seems to be working fine on desktop and mobile Firefox browsers, but I am facing an issue with mobile Chrome when trying to subscribe to the event strea ...

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...