When trying to extract information from a v-for loop and pass it into a method, I keep

After sending an array of data objects into a child component via props, I proceeded to use a v-for loop to display the elements exactly how I intended:

 <div class="col-md-3" v-for="product in products" :key="product.id" v-if="product.id <= 8" >
    <div>{{ product.name }}</div>
    <button @click="buyProduct">
</div>

Following that, I implemented this method:

 buyProduct(){
      console.log('bought');
      const order = {
        orderId: this.product.id,
        orderName: this.product.productName,
        orderImg: this.produc.image,
        orderOriginalPrice: this.product.originalPrice,
        orderdiscountPrice: this.products.discountPrice,
        orderQuantity: this.quantity, 
        
      };
        console.log(this.products);
    }

However, I encountered an error in the console stating: "TypeError: Cannot read property 'id' of undefined"

Any suggestions or solutions on how to retrieve the values of the clicked products would be greatly appreciated.

Answer №1

It seems that the error is occurring in this particular line of code: orderId: this.product.id,

Chances are, you have not initialized this.product. A better approach would be to pass the clicked product as a parameter to your buyProduct method:

<button @click="buyProduct(product)">buy me</button>

and

buyProduct(product) {
    ...
    orderId: product.id
    ...
}

It's not recommended to mix v-for and v-if in the template. Instead, consider using a computed property if you need to further filter the passed products:

computed: {
   filteredProducts() {
       return this.products.filter(p => p.id <= 8)
   }
}

Then you can use

v-for="product in filteredProducts"

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

Vue JS Image Path

I have a Vue.js structure file that looks like this: --assets ----image ------my-image.png ------my-image2.png --components ----user ------userStart.vue To display the images using an array object, my code in userStart.vue is as follows: ...

Loading objects with textures in Three.js using the objloader

For the past few weeks, I've been diving into Three.js and managed to successfully apply a texture to a cube I created directly in the code. However, when I attempted to load an OBJ file using OBJLoader, I ran into issues trying to load simple png or ...

Retrieve information using an AJAX call

There is JSON data stored in a file that I need to read. The correct file data is printed to the console.log. What steps should I take to assign this data to variable x? Currently, when I execute the code, x ends up being undefined. function getData() { ...

What is the best way to attach a CSS class to a button in Vue by using the "or" condition

Can you explain the correct way to use or in v-bind:class in vue js? <a class="button btn btn-default is-info" style="float:right;" v-on:click="clearSearchItem" v-bind:class="{'disabled': searchItem=='&a ...

A guide on selectively removing a value from a javascript object when calling setState in ReactJS

updateDishDetails(id, quantity) { if (quantity !== 0) { this.setState( prevState => ({ bookingFormData: { ...prevState.bookingFormData, dishDetails: { ...prevState.bookingFormData.dishDe ...

Troubleshooting inactive CSS hover animation

Greetings! I'm facing an issue with a CSS hover animation. Here are two demos I've created: In the first DEMO, the animation works perfectly. However, in the second DEMO, it doesn't seem to be functioning. On the second demo, there are two ...

Implementing a Search Box feature in React-leaflet version 3.1.0

Struggling to incorporate a searchbox feature into my react app. Encountering the error message "Attempted import error: 'MapControl' is not exported from 'react-leaflet'" with the latest version of react-leaflet. import { MapContainer, ...

Unknown custom element error in Laravel and Vuetify

I encountered errors in my Laravel project, specifically with custom elements like this. [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found ...

Sorting through JSON information based on specific attributes and criteria

Consider this JSON object: { 'name' : 'John', 'friends' : [ { 'id' : 1, 'name' : 'George', 'level' : 10 }, { 'id' : 2, 'name ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...

Using a template element for looping over an array with conditional rendering

I'm facing a challenge with conditionally rendering elements in a list using Petite-Vue. When I try to place a <li> tag with a v-if attribute inside a <template> tag with a v-for attribute, an error is generated: Uncaught (in promise) Ty ...

What is the best method for streaming files from Java to the browser while preventing the user from downloading and saving the file?

I'm new to this and feeling a bit lost. Here's the situation: I have a web app (built with JavaScript/Reactjs) and a backend (Java using Liferay API) The server contains files (File A, B, C, etc.) of various types: pdf, excel, audio, txt, etc. ...

Gaining access to the isolated scope of a sibling through the same Angular directive led to a valuable discovery

I am currently working on an angularjs directive that creates a multi-select dropdown with a complex template. The directives have isolated scopes and there is a variable called open in the dropdown that toggles its visibility based on clicks. Currently, t ...

At times, the Angular Modal Dropdown may unexpectedly open in an upward direction

Dealing with an AngularJS modal that contains a dropdown menu. The menu list is quite extensive. Most of the time, around 70%, the menu drops down in the lower direction which is fine. However, approximately 30% of the time, the dropdown menu appears in ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

Exploring the possibilities of querying Firestore data with dynamic user input

I am facing an issue with my code and struggling to find the right solution. My goal is to build a filter that, upon clicking on each option, will automatically fetch data from firestore. https://i.sstatic.net/ktLuE.png Within my Redux Saga, I have the ...

The request for JSON parsing encountered a failed attempt, resulting in an error while trying to parse the JSON

var userData = { "emailAddress": document.getElementById('emailAddress').value, "password": document.getElementById('password').value } var userDataString = JSON.stringify(userData); alert(userDataString); var url = "url"; var ...

"Exploring the World Wide Web with JavaScript and Ajax in Internet

Is there a way to include a Javascript snippet at the end of some ajax content? It seems to be functioning properly in Firefox, but when I try it in Internet Explorer, the script is printed out without being executed. <script type="text/javascript"&g ...

Ensuring the validation of multiple ValidationObservers in Vue

In my ChangeInfo screen, I have three components representing ValidationObservers. When all three are valid, I set the variable showModal = true to display a success notification modal. However, if any of the three components have an error, showModal remai ...

Vue unit testing for reactive state functions

Unit testing is a new concept for me, especially when dealing with reactive state in components. I am looking to write unit tests for a component that contains reactive state. Below is an example of the test component: <script setup lang="ts" ...