Looking to retrieve a specific data element within Vue.js?

Here's a thought-provoking query for you. Imagine I have some data stored in an element in the form of an array like this:

   data: {

     product: socks,

     variants: [
      {
    variantId: 2234,
    variantColor: 'Green',
    variantQuantity: 0,
  },
  {
    variantId: 2235,
    variantColor: 'Blue',
    variantQuantity: 10,
  }

}

The burning question is, how can I pin down a specific variantQuantity by merely hovering over a particular div?

Let's dissect the full code:

HTML:

<div class="product-image">
  <img :src="image" />
</div>

<div class="product-info">
  <h1>{{ product }}</h1>
  <p v-if="inStock">In Stock</p>
  <p v-else :class="{ outOfStock: !inStock }">Out of Stock</p>

  <ul>
    <li v-for="detail in details">{{ detail }}</li>
  </ul>


    <div class="color-box"
         v-for="variant in variants" 
         :key="variant.variantId"
         :style="{ backgroundColor: variant.variantColor }"
         @mouseover="updateProduct(variant.variantImage)"
         >
    </div> 

    <button v-on:click="addToCart" 
      :disabled="!inStock"
      :class="{ disabledButton: !inStock }"
      >
    Add to cart
    </button>

  <div class="cart">
    <p>Cart({{ cart }})</p>
  </div>

</div>

Javascript:

var app = new Vue({
el: '#app',
data: {
product: 'Socks',
image: 'https://dl.dropboxusercontent.com/s/9zccs3f0pimj0wj/vmSocks-green-onWhite.jpg?dl=0',
inStock: false,
details: ['80% cotton', '20% polyester', 'Gender-neutral'],
variants: [
  {
    variantId: 2234,
    variantColor: 'green',
    variantImage: 'https://dl.dropboxusercontent.com/s/9zccs3f0pimj0wj/vmSocks-green-onWhite.jpg?dl=0',
variantQuantity: 0
  },
  {
    variantId: 2235,
    variantColor: 'blue',
    variantImage: 'https://dl.dropboxusercontent.com/s/t32hpz32y7snfna/vmSocks-blue-onWhite.jpg?dl=0',
variantQuantity: 10
  }
],
cart: 0
},
methods: {
addToCart() {
  this.cart += 1
},
updateProduct(variantImage) {
  this.image = variantImage
}
}
})

Answer №1

To implement the functionality of updating product information, you can integrate variant.variantQuantity into the mouseover event-handler expression:

<div v-for="variant in variants" 
     @mouseover="updateProduct(variant.variantImage, variant.variantQuantity)"
     >

Furthermore, incorporate a data property for quantity and adjust the handler to account for this new property:

data() {
  return {
    quantity: 0,
    // ...
  };
},
methods: {
  updateProduct(variantImage, variantQuantity) {
    this.image = variantImage;
    this.quantity = variantQuantity;
  },
  // ...
}

Check out a demo based on your CodePen here

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

I would like to give the option for file uploads, but the form refuses to submit unless a file is uploaded

I've recently developed a form in React and React Bootstrap, and I've encountered an issue with the file upload feature. I want the file upload to be optional, but when I try to submit the form without uploading a file, it doesn't work as ex ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Numerous Data Tables on a single page with varying parameters

I'm facing a scenario where I have two dataTables on the same page. Referencing this example: https://datatables.net/examples/basic_init/multiple_tables.html Everything seems to be working fine, but both tables share common parameters such as buttons ...

Personalize the landing page for your IPython notebook

Is it possible to customize the landing page of an iPython notebook server (version 2.3)? By that, I mean altering the starting page (for example: http://localhost:8888/tree) to show a message like Welcome to John Doe's i[Py] Notebook or changing the ...

Ways to combine text styling with images, stroke effects, and shadows all at once

I am looking to enhance my text with a background image, a text-stroke, and a text-shadow. The issue I am facing is that the text-shadow appears on top of the background image. Does anyone have a solution for placing the shadow behind the image? If you te ...

Passing Optional Parameters to AngularJS Modal

Is there a way to pass an optional parameter to my angularJS modal? Let's take a look at the code: TRIGGER CONTROLLER: $modal.open({ templateUrl: 'UploadPartial.html', controller: 'photos.uploadCtrl', resolve: { presele ...

Using Javascript in the Model-View-Controller (MVC) pattern to load images stored as byte

Despite the numerous solutions available on Stack Overflow, I am still unable to get any of them to work... I am faced with the challenge of setting the "src" attribute of an image tag using a byte array obtained from an ajax call to my controller in Java ...

Error Encountered: AJAX Request Failed with 400 Bad Request

I've been using mithril.js to communicate with my node back-end. I followed the documentation and added an AJAX request, but there seems to be limited information available on mithril. Encountered Error: mithril.js:2130 POST http://localhost:3000/a ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

I tried running the sample program from the website in mongoose, but I encountered a persistent error: "TypeError: fluffy.speak is not a function."

const mongoose = require('mongoose'); main().catch(err => console.log(err)); async function main() { await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }); console.log("Connection successfu ...

Issue with JavaScript variables (I presume) - there seems to be a conflict when one variable is used alongside another

I am attempting to conduct a test that requires displaying the number of attempts (each time the button is pressed) alongside the percentage of successful attempts, updating each time the button is clicked. However, I've encountered an issue where onl ...

The issue of JavaScript failing to connect to the HTML file

As I work on my basic HTML file to learn Javascript, I believed that the script was correctly written and placed. Nevertheless, upon loading the file in a browser, none of the script seems to be functioning. All of my javascript code is external. The follo ...

Setting a default value in a dynamic dropdown using AngularJS

I could really use some assistance with my issue as I am fairly new to working with AngularJS. My dilemma is related to setting the default value in a select option when there is only one item available due to it being a dynamic select option. Though there ...

Fetching post value via AJAX in Codeigniter views: A step-by-step guide

Having issues receiving Ajax response as it is coming back null. The HTML layout includes: <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <select class="form-control" class="form-control" id="choose_country"& ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

Issue with an Angular filter for formatting a lengthy JSON string onto separate lines within an HTML document

Just starting out with coding and working in Angular, I'm trying to display JSON data from Firebase in HTML. Here's the specific call I'm using: <p>{{workout[0].box.info.training.strength.exercise[1].movement.freetext }}</p> Th ...

The "body" object cannot be accessed in a post request made from an Express router

I am currently utilizing Express router functions to manage some POST requests. Client.js let data = { endpoint: "Blah Blah"; }; return fetch('/api/get-preferences/', { method: 'POST', headers: { 'Content-Type': & ...

Text directly in the middle

Explanation In an attempt to replicate the "middle centered text" feature, such as "Responsive Front-end Development," on this website, I am currently exploring various methods. As a newcomer to web development, I have searched for templates to provide me ...

Is it possible to verify the authenticity of JSON data retrieved from

I'm currently working on validating JSON input from users and came across a challenge. I've found a way to check if the text a user enters is valid JSON using a simple function, like below: function IsJsonString(str) { try { JSON.par ...