Tips for efficiently showcasing array responses in Vue.js and Laravel

I am looking to showcase array data within a .vue file, but I am uncertain about the process. This is my attempt:

<template>
    <div id="app">
        <table class="table table-striped">
          <thead>
             <tr>
                <th>Project Name</th>
                <th>Type</th>
             </tr>
          </thead>
          <tfoot>
             <tr v-for="user in info">
                <th>{{ user.data.user.assigned_projects.name }}</th>
                <th>{{ user.data.user.assigned_projects.type }}</th>
             </tr>
          </tfoot>
        </table>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  el: '#app',
  data() {
    return {
      info: null
    }
  },
  mounted() {
    axios
      .get('http://api_url')
      .then((response) => {
        this.info = response.data
      })
  }
}
</script>

Below is an illustration of an API response example:

{
   "response":{
      "error":{
         "error_code":0,
         "error_msg":"",
         "msg":""
      },
      "data":{
         "user":{
            "id":1,
            "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a3aba7afaa86a7a2a2b4a3b5b5e8a5a9ab">[email protected]</a>",
            "first_name":null,
            "last_name":null,
            "photo_url":null,
            "organisation":null,
            "own_projects":[
            ],
            "assigned_projects":[
               {
                  "id":10,
                  "name":"test project",
                  "description":"cool stuff",
                  "image_url":"http://image_url",
                  "timezone":"UTC",
                  "owner":15,
                  "created_by":15,
                  "created_at":"2019-02-26 16:37:03",
                  "updated_at":"2019-02-26 16:37:03",
                  "pivot":{
                     "user_id":1,
                     "project_id":10
                  }
               },
               {
                  "id":8,
                  "name":"test project 2",
                  "description":"",
                  "image_url":"",
                  "timezone":"UTC",
                  "owner":15,
                  "created_by":15,
                  "created_at":"2019-02-21 18:36:55",
                  "updated_at":"2019-02-21 18:36:55",
                  "pivot":{
                     "user_id":1,
                     "project_id":8
                  }
               }
            ]
         }
      }
   }
}

Answer №1

Typically, when using the v-for directive, it follows this structure: v-for="item in items", where items points to an array or object in your data.

In this case, the data path to access assigned_projects[] is

info.response.data.user.assigned_projects
. Therefore, the correct usage of v-for would be:

<tr v-for="project in info.response.data.user.assigned_projects" :key="project.id">
  <th>{{ project.name }}</th>
  <th>{{ project.id }}</th>
</tr>

new Vue({
  el: '#app',
  data() {
    return {
      info: null
    }
  },
  mounted() {
    // Data assignment here 
});
  }
})
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 8px;
}

tfoot th {
  font-weight: normal;
}

tr:nth-child(even) {
  background-color: #f2f2f2
}
<script src="https://unpkg.com/vue@2.x"></script>

<div id="app">
  <table>
    <thead>
      <tr>
        <th>Project Name</th>
        <th>Type</th>
      </tr>
    </thead>
    <tfoot>
      <tr v-for="project in info.response.data.user.assigned_projects" :key="project.id">
        <th>{{ project.name }}</th>
        <th>{{ project.id }}</th>
      </tr>
    </tfoot>
  </table>
</div>

If you want a cleaner template for better readability, consider implementing a computed property:

// Template
<tr v-for="project in projects" :key="project.id">...</tr>

// Script
computed: {
  projects() {
    // Return empty array if `this.info` is not yet defined
    return this.info && this.info.response.data.user.assigned_projects || [];
  }
}

new Vue({
  el: '#app',
  data() {
    return {
      info: null
    }
  },
  computed: {
    projects() {
      return this.info && this.info.response.data.user.assigned_projects || [];
    }
  },
  mounted() {
    // Data initialization here 
});
  }
})
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 8px;
}

tfoot th {
  font-weight: normal;
}

tr:nth-child(even) {
  background-color: #f2f2f2
}
<script src="https://unpkg.com/vue@2.x"></script>

<div id="app">
  <table>
    <thead>
      <tr>
        <th>Project Name</th>
        <th>Type</th>
      </tr>
    </thead>
    <tfoot>
      <tr v-for="project in projects" :key="project.id">
        <th>{{ project.name }}</th>
        <th>{{ project.id }}</th>
      </tr>
    </tfoot>
  </table>
</div>

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

Utilizing Ajax to dynamically update the content of a div element

As a newcomer to Ajax, I am trying to use xmlhttprequest to dynamically change the content of a div by fetching HTML from different URLs. However, my code doesn't seem to be working as expected. Can someone help me identify what I might be doing wrong ...

Troubleshooting: JQuery dropdown selection not updating image display

I am trying to create a select menu that changes the car image when a user selects a different model, but for some reason it is not working. Here is what I have tried: <h2 class="model">A6 <img src="images/3.jpg" id="image" width="544" height="2 ...

You cannot use res.json before res.redirect in Express.js

Hey there, currently I'm utilizing the express module in Node JS res.json({ auth: true, token: token, message: "success" }); res.redirect('/'); I need to send some JSON data first and then redirect. However, I encountered this err ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

Loading Animation for Pages and Tables

I'm experiencing a choppy and sudden transition when switching between two pages that contain tables populated using ng-repeat. Upon loading, the footer is positioned halfway up the page below the table heading until the table loads and the layout adj ...

What is the best approach for handling an AJAX request on the server side?

Consider the function below: $.ajax({url:"http://127.0.0.1:8080", data: "123", success: function(response, textStatus, jqXHR) { alert(response); }, error: function(jqXHR, textStatus, errorThrown) { alert("An er ...

Searching for multiple filtered items in Vue.js

When working with Vue js, searching through a list is straightforward. However, when dealing with a large dataset of 1000 records and needing to apply specific filters for user searches, I find myself at a loss. Is there a plugin or method that can help me ...

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

What is the best way to exclude an external HTML file from being displayed on the home page?

shopping_cart.php <div id="main-container"> <div class="container"> <span class="top-label"> <span class="label-txt">Shopping Cart</span> </span> <div class="content-area"> <div class="con ...

Disappearing modal in Bootstrap 5 does not eliminate the backdrop

When using Bootstrap 5, I create my modal like this: var myModal = new bootstrap.Modal(document.getElementById('scheduleMeetingModal'), { backdrop: 'static' }); myModal.show(); Later on, when I want to hide the modal in another fun ...

What steps should I take to prompt Postman to interact with a Web API?

I have recently installed the Postman plugin for Chrome and I am curious about how to use it to call my web API. Currently, I am making an AJAX call in JavaScript with the following code: alert("Getting security token"); // Do AJAX call to get security t ...

Refining search outcomes using multiple Multiselect boxes in VueJS

In my Vue component, I have successfully displayed results from a data object and created multiple multiselect boxes. However, I am facing challenges with filtering. I understand how to set and compare a single value from the multiselect for displaying sp ...

Is there a way to generate a modal list of values by utilizing bootstrap and angular, while incorporating spring boot as the backend technology?

I'm working on developing a generic "List of Values" feature, which will be a searchable modal containing a natural identifier and description. I have successfully built an AngularJS application in Spring Boot to accomplish this task, but unfortunatel ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

Utilizing Next.js routing to accommodate two distinct subdomains on a single website

I am looking to develop a new platform using Next.js (React.js and React-router). The platform will have two distinct spaces - one for users and another for the owner to manage all users. To achieve this, I plan on splitting both areas into two subdomains: ...

Tips on submitting JSON data to a server

I need the data to be structured like this {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c3f18121e1613511c1012">[email protected]</a>","password":"1"} but it is currently appearing like this { & ...

Steps for implementing drag-and-drop feature for a div in a template

I am looking to implement draggable functionality on a div element dynamically. The unique id for the div is generated using the code snippet below: var Exp=0; view.renderFunction = function(id1){ var id= id1 + Exp++; $("#"+id).draggable(); }; In my ...

Modify the layout of the date selector to display weekdays instead - material ui

How can I change the datepicker format to display weekdays (Monday, Tuesday,..) instead of MM/dd/yyyy? Currently, the datepicker is set up with the format format="MM/dd/yyyy". Would it be possible to modify this? Here is the source code: <MuiPickers ...

How can you use Vue.js with NW.js to seamlessly open a link in the user's preferred browser?

Essentially, the question lies within the title itself, but allow me to elaborate. I have a proposed solution for this issue, however, I believe it lacks practicality and I am seeking a more efficient approach. For instance, opening one link is not a prob ...