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

Tips for implementing conditional app.use() in nestJS backend strategies?

Trying to incorporate helmet into my nestJS application. I also require the inclusion of graphqlUploadExpress. How can I properly utilize the usesUpload condition to implement either helmet alone or along with upload? import { NestFactory } from '@nes ...

Using jQuery to show/hide linked CSS3 animations upon Mouseenter/Mouseleave events

Exploring the capabilities of animate.css and jQuery within a bootstrap environment has been quite interesting for me. However, I've encountered a major issue! I am attempting to trigger animations on mouseenter / mouseleave, which led me to create a ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

Unveiling the hidden: Leveraging Python to extract elements not visible in HTML, yet present in Chrome's "Inspect Element" tool

Hello Python Experts! I'm diving into the world of Python and working on a program to retrieve data from a webpage. If the page returned all the information in its HTML source, there wouldn't be an issue as it's easily viewed in Chrome. Howe ...

Implementing multiple filters with jQuery

Make a Selection `<select class="form-control" id="technology"> <option name="sort" value="2g" id="2g"gt;2G</option> <option name="sort" value="3g" id="3g"&g ...

What is the process for retrieving an image from firebase storage?

I need some help accessing an image that I uploaded to Firebase storage. I followed the instructions provided in https://firebase.google.com/docs/storage/web/download-files but unfortunately, it's not working for me. My goal is quite simple: I have a ...

Creating JavaScript Objects from HTML Form data with the help of serializeJSON

Struggling extracting HTML form data into the required JSON format for server communication. Despite following a guide, I can't get the output right. Managed to extract question keys and values, but labeling is tricky. Current Output: {"Question1":" ...

Using React.js - What is the process for submitting a form automatically when the page loads?

Upon loading the page, I have a form that needs to be displayed. Here is the code snippet: <form name="myform" method="POST" className={classes.root} target="mydiv" action="https://example.com/submit" onLoad= ...

The random string generator is selecting a unique string for both the server and client side

I am facing an issue with a component in Next.js (v14.2.1) where I need to display a random string while fetching data. Despite my attempts, I can't seem to maintain the same string on both server and client sides. Below is the code snippet I am curr ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...

Reorganize external dependencies in the wwwroot directory using gulp

In my development setup using VS 2015, ASP.net vnext, Angular 2, Typescript, and gulp.js, I have successfully automated the process of moving my scripts/**/*.ts files to the wwwroot/app folder. Now, I am looking to extend this automation to include my libr ...

The process of accessing a file object by using the file path given

Is there a way to retrieve the file object of an image that is stored in my website's folder without using "input type = "file"? The image is already saved on the website. Here is what I have tried so far: var file = new File([""], "../writeto/image. ...

The issue with the vue-carousel arises from an uncaught TypeError in which it is unable to read properties of undefined while trying to access '_c'. This problem occurs within the vue-carousel.min.js file

I encountered an error when using the Carousel component from the plugin. The error message is as follows: vue-carousel.min.js:6 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_c') at Proxy.r (vue-carousel.min.js: ...

top margin is functioning properly in Internet Explorer, but not in Google Chrome

margin-top is behaving differently in IE compared to Google Chrome. Two menus are supposed to be displayed one above the other in my design. The issue lies in the line margin-top:30%; within .anothermenu ul. In Chrome, the second menu appears above the f ...

Jest's inability to execute a test suite for a component that imports an asynchronous function

Recently, I migrated a project from AngularJS to Vue. Post-migration, I attempted to introduce unit tests using Jest. Initially, the tests around smaller components and services ran smoothly without any issues. However, when I tried testing more complex co ...

What is the correct way to assign a property to a function's scope?

Lately, I've been delving into Typescript Decorators to address a specific issue in my application. Using a JS bridge to communicate TS code between Android and iOS, we currently define functions as follows: index.js import foo from './bar' ...

A computer program designed to determine a series of numbers needed to complete a square grid

Given the numbers 1, 2, 3, 4, 5, 6, 7, 8, I am seeking to replace the x's in such a way that each side adds up to the number in the center. *-*---*-* |x| x |x| *-*---*-* |x| 12|x| *-*---*-* |x| x |x| *-*---*-* Initially, I have iterated over the num ...

Create bubble diagrams to display detailed information within a line graph using Chart.js

After creating a line chart with chartJS, I am looking to enhance it by adding bubbles to indicate specific data points such as the mode, red, and amber levels. While I have successfully drawn the lines on the chart, I am unsure of how to incorporate these ...

Customize Input Values by Selecting an Option with jQuery-UI Autocomplete

Hello there, I am a newcomer to java-script and could really use some help. My goal is to have the data in the country field automatically populated when a user enters data into the city field. I have an xml file: <ROWSET> <ROW> <city>&l ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...