The looping function in Vue.js data is not functioning properly

Currently, I am developing a shopping cart system using Laravel session and Vue.js. Below is a snippet of my Vue.js code where I loop through the products and add them to the cart/session on click.

<div v-for="product in products">
      <div class="card" >
        <div class="card-header">{{product. name}}</div>
        <div class="col-md-4">
            <div class="card-body">
                    <img :src="product.image">
                    <p>{{product.price}}</p>
                    <p>{{product.category_id}}</p>
                </div>
                <button class="btn btn-primary" @click="addProductToCart(product)">Add to cart</button>
            </div>
        </div>        
    </div>

Below is a snippet of the Vue.js code:

export default {

    data:function(){
        return {
            lists:[]// everything is pushed in lists array
        }


methods:{
        addProductToCart(product){
           // alert(product)
            axios.get('/cart',{
                 params: {
                    product: product
                }
            }).then((response) => {
        });

mounted:{
  axios.get('/list')
            .then(function (resp) {
                console.log(resp)
                app.lists=resp.data
            })}

This is how I have structured my controller:

public function StoreInCart(Request $request) {
        //dd($request->get('product'));
         $request->session()->push('product',$request->product);
         return session('product');

    }
    public function listProduct(Request $request){
        $product = $request->session()->get('product');
        return $product;
    }

When I store data in Vue.js, it looks like this:

lists:Array[7]
0:"{"id":1,"name":"Keyshawn McDermott Sr.","description":"Error aut quia id dolorem est aut doloribus nesciunt. Quod nihil tenetur ea id voluptas molestias id. Debitis amet dolor est fugiat sed autem.","category_id":1,"price":59,"image":"http://loremflickr.com/400/300?random=36","created_at":"2019-07-16 10:12:27","updated_at":"2019-07-16 10:12:27"}"
1:"{"id":2,"name":"Marlene Reichert","description":"Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae.","category_id":3,"price":76,"image":"http://loremflickr.com/400/300?random=71","created_at":"2019-07-16 10:12:27","updated_at":"2019-07-16 10:12:27"}"
2:"{"id":1,"name":"Keyshawn McDermott Sr.","description":"Error aut quia id dolorem est aut doloribus nesciunt. Quod nihil tenetur ea id voluptas molestias id. Debitis amet dolor est fugiat sed autem.","category_id":1,"price":59,"image":"http://loremflickr.com/400/300?random=36","created_at":"2019-07-16 10:12:27","updated_at":"2019-07-16 10:12:27"}"
3:"{"id":1,"name":"Keyshawn McDermott Sr.","description":"Error aut quia id dolorem est aut doloribus nesciunt. Quod nihil tenetur ea id voluptas molestias id. Debitis amet dolor est fugiat sed autem.","category_id":1,"price":59,"image":"http://loremflickr.com/400/300?random=36","created_at":"2019-07-16 10:12:27","updated_at":"2019-07-16 10:12:27"}"
4:"{"id":2,"name":"Marlene Reichert","description":"Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae.","category_id":3,"price":76,"image":"http://loremflickr.com/400/300?random=71","created_at":"2019-07-16 10:12:27","updated_at":"2019-07-16 10:12:27"}"
5:"{"id":18,"name":"Heidi Kuhlman","description":"Eveniet et dolorum aut magnam ut amet reprehenderit eveniet. Nihil incidunt voluptas aut amet et.","category_id":7,"price":274,"image":"http://loremflickr.com/400/300?random=2","created_at":"2019-07-16 10:12:27","updated_at":"2019-07-16 10:12:27"}"

Unfortunately, due to this data format, I am unable to loop through the lists successfully:

<div class="card-body" v-for="list in lists">
   {{list.name}}// i got nothing
</div>

I am struggling to loop through the data stored in the Lists Array. Any suggestions on how to overcome this challenge would be greatly appreciated. Thank you.

Answer №1

If you want to store product details as a JSON object (in this case, it's a JSON string, not JSON objects), you can modify the push function of your controller like this:

$request->session()->push('product',json_decode($request->product));

Here is the complete code snippet:

public function StoreInCart(Request $request) {
    $request->session()->push('product',json_decode($request->product));

    return session('product');

}
public function listProduct(Request $request){
    $product = $request->session()->get('product');
    return $product;
}

Answer №2

Considering the suggestion from Samir Mammadhasanov, looping through the Array as mentioned can be achieved by using the following code snippet:

    <div class="content-section" v-for="item in items">
       {{JSON.parse(item).title}}
    </div>

Answer №3

Make sure to use JSON.parse() on each item within the list. It's important to remember that these are JSON strings and have not been converted to objects yet.

One effective approach could be to create a separate component for each list item and then utilize a computed property to return the parsed object. Here's an example:

parsedData() {
    return JSON.parse(this.jsonString);
}

Answer №4

Although this may not directly answer your question, I suggest incorporating a key attribute in your Vue.js List Rendering based on the blade code you provided.

<div v-for="product in products" :key="product.id">
      <div class="card" >
        <div class="card-header">{{product. name}}</div>
        <div class="col-md-4">
            <div class="card-body">
                    <img :src="product.image">
                    <p>{{product.price}}</p>
                    <p>{{product.category_id}}</p>
                </div>
                <button class="btn btn-primary" @click="addProductToCart(product)">Add to cart</button>
            </div>
        </div>        
    </div>

OR

 <div v-for="(product,index) in products" :key="index">
          <div class="card" >
            <div class="card-header">{{product. name}}</div>
            <div class="col-md-4">
                <div class="card-body">
                        <img :src="product.image">
                        <p>{{product.price}}</p>
                        <p>{{product.category_id}}</p>
                    </div>
                    <button class="btn btn-primary" @click="addProductToCart(product)">Add to cart</button>
                </div>
            </div>        
        </div>
 

From Vue Docs:

It is advised to use a key attribute when iterating over an object to ensure consistency in the enumeration order of Object.keys(). https://v2.vuejs.org/v2/guide/list.html

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

Creating dynamic forms using AngularJS and the ng-repeat directive

i am working with AngularJS dynamic forms . According to my userid value i generated multiple form field with same model name using ng-repeat. i am not able to get this input model values due to this ng-repeat. in this example i am using static userid data ...

What is the best way to remove the hover effect from a specific element within a div?

I am looking to achieve a specific hover effect where the white part does not darken when hovering over a certain element within its child elements. Here is the HTML code I have: <div className= {css.searchBarDiv}> <div className={css.searchBar ...

Ways to remove identical key from distinct object within an array

Is there a way to remove specific date keys from multiple objects in an array of objects? I attempted to use a for loop and the delete function, but it doesn't seem to be working. var data = matchScoreData.tbl_FallOfWicket; matchScoreData.tbl_Fall ...

The HTML embed element is utilized to display multimedia content within a webpage, encompassing

Currently, I am working on a static website for my Computer Networks course. Students need to be able to download homework files in PDF format from the website. I have used embed tags to display the files online, but I'm facing an issue where the embe ...

Three.js is currently rendering a blank canvas in pure white

After following the tutorial at , my browser only displays a white window. I attempted separating the files into js and html, but no luck. What I have already tried: experimenting with adding/deleting the nomodule parameter in the script tag utilizing a ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

Determine the number of JavaScript functions present on a webpage using JavaScript

Hey there! I'm interested in counting the javascript functions on a specific page and then sending this count via ajax. Do you think it's possible to do this using javascript? What would be the best approach? Thanks in advance! Just to explain f ...

Having trouble with getStaticProps serialization error in Next.js?

I encountered an error in my Next.js application that reads as follows: Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only ret ...

Vue recalculate computed value only when result changes

Let's dive into a simplified version of the problem at hand: export default { data () { return { i_change_alot: 0, }; }, mounted() { setInterval(() => { this.i_change_alot = Math.random(); ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

Numerous CSS/JS Dropdown Menus

I am seeking the ability to implement a dropdown through CSS in various locations within my HTML prototype. This implies that I require the capability to position multiple dropdowns anywhere on the page. Currently, I utilize this method to generate a sing ...

Checking for a specific value in a hasMany relationship with Laravel's Query Builder

Struggling to implement conditional logic in my query builder and can't seem to locate the appropriate function... For instance, let's consider the following scenario: We have a model A linked to multiple instances of model B. Model B has column ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Determine if a radio button is selected using Jquery

I am currently working on a script that should uncheck a radio button if it is checked, and vice versa. However, I'm facing an issue where the script always registers the radio button as checked even when it's not. Below is the code snippet in q ...

What distinguishes a WAV file recorded from a user's microphone versus a WAV file imported from a separate file? Identifying the unique characteristics that may be causing bugs

Currently, I have two methods available for sending a WAV file to the server. Users can either upload the file directly or record it using their microphone. After the files are sent, they undergo a similar processing workflow. The file is uploaded to S3 an ...

Why isn't Freichat displaying the name of the user who logged in?

After creating my own small social networking site, I decided to add a chat script called freichat. However, I am facing an issue where when a user logs in, their name appears as "Guest102" instead of their actual name. I am quite confused by this problem ...

Tips for resolving the issue of the '$interval is not a function' error in AngularJS

When I click on the up/down arrows, I am attempting to continuously increase/decrease a value using AngularJS $interval function. However, I keep encountering an error message that says "TypeError: $interval is not a function." Can someone please help me s ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

What is the method for displaying a server-fetched error message in a form field using Ant Design Vue 3?

My current challenge lies in setting error messages retrieved from the Laravel backend and displaying them on each field that has an error. The data structure for the errors is as follows: { 'errors': { 'email' : ['The Email ...