How can you showcase the content of an object within an array?

I am currently working on a project component that involves retrieving and logging data. However, I am facing an issue with accessing objects within my array of clients to display them properly in my table.

Here is the script I am using:

<script>
export default {
  data: () => ({
    clients: [],
  }),

  methods: {
    getClients() {
      this.$api
        .get("/api_v1/clientes", {
        })
        .then((response) => {
          this.clients = response.data[0];
          console.log(response.data);
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },

  mounted() {
    this.getClients();
  },
};
</script>

Below is the code for my table:

 <tbody>
          <tr v-for="client in clients" v-bind:key="client.id">
            <td>{{ client.id }}</td>
            <td>{{ client.name }}</td>
            <td>{{ client.email }}</td>
            <td>{{ client.documents.cpf || client.documents.cnpj }}</td>
            <td>{{ client.documents.celular }}</td>
            <td>{{ client.status }}</td>
            <td v-if="client.address">
              {{ `${client.address.localidade} / ${client.address.uf}` }}
            </td>
            <td v-else>-</td>

            <td>
              <a :href="`/see-client/${client.id}`"><i class="icon-magnifier"></i
              ></a>

              <i class="icon-check" style="color: green"></i>
              <i class="icon-close" style="color: red"></i>
            </td>
          </tr>
        </tbody>

This is the controller snippet:

  public function index(Request $request)
    {
        $data = [
            'pag' => 'All clients',
            'link' => '/'
        ];

        return view('clients.index', $data);
    }

The relevant data can be found here. If anyone has suggestions or alternative approaches utilizing Vue2, feel free to share. As this is one of my first major projects, I appreciate your understanding and any advice you may have. Thank you for your time!

Answer №1

Here is a tip on how to handle your client data:

this.clients = response.data[0];

response.data holds an array of clients. By referencing .data[0], you specifically extract the first client from the array.

However, the next step in the code attempts to iterate over a single client instead of the entire array of clients.

<tr v-for="client in clients" v-bind:key="client.id">

To solve this issue, consider modifying the assignment like so:

this.clients = response.data;

If the above solution doesn't work due to a complex data structure, try the following alternatives:

this.clients = response.data.data;

Or perhaps (if there are multiple nested data properties):

this.clients = response.data.data.data;

Answer №2

Upon reviewing your code, I believe there are some areas that could benefit from refinement.

Firstly, let's address the JavaScript section:

<script>
export default {
  data() {
    return {
      clients: [],
    };
  },

  methods: {
    async getClients() {
      try {
        const response = await this.$api.get("/api/clientes");

        this.clients = response.data.data;
      } catch (e) {
        console.log("Check this error: ", e);
      }
    },
  },

  async mounted() {
    await this.getClients();
  },
};
</script>

Next, update your API controller logic to utilize response()->json(...):

public function index(Request $request)
{
  // Your retrieve logic...

  return response()->json($data);
}

Once these changes are made, ensure that your Vue component is able to correctly retrieve information and display it within the tbody as follows:

<tbody>
  <tr v-for="client in clients" v-bind:key="client.id">
    <td>{{ client.id }}</td>
    <td>{{ client.name }}</td>
    <td>{{ client.email }}</td>
    <td>{{ client.documents.cpf || client.documents.cnpj }}</td>
    <td>{{ client.documents.celular }}</td>
    <td>{{ client.status }}</td>
    <td v-if="client.address">
      {{ client.address.localidade }} / {{ client.address.uf }}
    </td>
    <td v-else>
      -
    </td>

    <td>
      <a :href="`/see-client/${client.id}`">
        <i class="icon-magnifier"></i>
      </a>

      <i class="icon-check" style="color: green"></i>
      <i class="icon-close" style="color: red"></i>
    </td>
  </tr>
</tbody>

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

How is it that my initial response appears correct in the first log, but then suddenly changes to a 1?

I've encountered a strange issue where the response appears correctly in the initial log, but later changes to a '1' when console.log(data); is called. The screenshot illustrates the pattern: https://i.sstatic.net/zaXcg.png If you expand ...

Obtain image source from Laravel server to be included in email

I am looking to track when someone has opened an email I sent. Currently, I am using a method that involves embedding a 1x1 pixel transparent image. I found this helpful resource: Detecting image load on server This is my current HTML code: <img src ...

Nuxt is unable to modify the data variable

When working with Vue in Nuxt, I often encounter an issue where changes to a variable in the data section of my component do not reflect in the HTML. For example: export default { data () { return { openPopup: '1' } }, methods: ...

Ways to display a variable within an HTML element

What could be causing variable a to be undefined? export default function Surah() { let a; const updateVariable = (id) => { a = id; console.log(a); }; return ( <div> <div> <button onClick={() => ...

Executing the Javascript function specified above upon the page being loaded

I'm fairly new to JavaScript, so please bear with me. I've got a JavaScript function on my page: <script type="text/javascript"> Sys.debug = true; var popup; Sys.require(Sys.components.popup, function () { popup = Sys.c ...

Why is a <script> tag placed within a <noscript> tag?

Lately, I've been exploring various websites with unique designs and content by inspecting their source code. One site that caught my attention was Squarespace, which had blocks of <script> tags within a <noscript> tag: <!-- Page is at ...

Dual Networked Socket.IO Connection

I have set up a node.js server with an angular.js frontent and I am facing a problem with Socket.IO connections. The issue arises when double Socket.IO connections open, causing my page to hang. var self = this; self.app = express(); self.http = http.Ser ...

The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

Implementing an object as a filter in an NG-repeat function

I've created multiple select dropdowns that are populated from a JSON file containing categories. My goal is to use the selections made by users in the dropdowns to filter a list of apps generated using ng-repeat. In my Plunker example http://plnkr. ...

Using a for loop in Flot to display data from a JSON file

I am working on creating a dynamic flot graph that will adjust based on the data provided. The information for my flot graph is in JSON format, and here's an example of the dataset: { "total":[[1377691200,115130],[1377694800,137759],[1377698400,1 ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

Follow button on LinkedIn is secure with Google Chrome's Content Security Policy set to script-src report-sample

Having an issue trying to add a LinkedIn Follow button to the website. It works perfectly in Firefox, but is not functioning in Chrome. The Console displays the following error: The source list for Content Security Policy directive 'script-src&apos ...

transfer a product attribute value to a different product attribute within the Magento platform

There is an attribute called Weight : Attribute Code: weight Scope: general Catalog Input Type for Store Owner: Text Field Values Required: yes Apply To: Simple Product, Bundle Product Allow HTML Tags on Frontend: yes Also, there is a General Weight attr ...

Is it possible to center an anchor link in React JS using Webpack, Sass, and Bootstrap 4?

Recently, I started delving into React JS and Webpack but encountered a perplexing issue. My goal is simple - to center an anchor link on the screen. However, despite trying various methods like inspecting the element, removing inherited styles, setting wi ...

Creating unique custom renders in Node.js

I am in the process of creating an API using node.js and express. I am interested in enhancing the standard res.send function from any of the external route files to format the response beforehand and include extra data. Is there a way to achieve this? A ...

Creating a powerful API controller in Laravel 5 using the Dingo package

I've been working on setting up a REST API using the Laravel 5 Dingo API package. Here is the routing code I have: $api->version('v1', function ($api) { $api->get('users/{id}', 'Api\V1\UsersController@sh ...

Requesting Axios.get for the value of years on end

I'm grappling with obtaining a JSON file from the server. The endpoint requires a year parameter, which needs to be set as the current year number as its value (e.g., ?year=2019). Furthermore, I need to fetch data for the previous and upcoming years a ...

Troubleshooting the 'ReferenceError: requestAnimationFrame is not defined' error in Vuetify unit testing

Running vue run test:unit with certain Vuetify components is resulting in the error outlined below: ReferenceError: requestAnimationFrame is not defined at VueComponent.mounted (dist/js/webpack:/src/components/VTextField/VTextField.ts:229:1) a ...