Home > front end >  Why I can't see my props from backend in my nuxt page?
Why I can't see my props from backend in my nuxt page?

Time:12-17

I'm making an index page nad I have to recover from my db customers data and insert it in a table element in my index page. I've set my props, mounted function with axios that get the data from the backend route and in a data function I return customers array,

my index.vue page:

<template>
  <div>
     <table v-if="customers">
  <tr>
    <th>name</th>
    <th>address</th>
  </tr>
  <tr>
    <td>{{ customers.name }}</td>
    <td>{{ customers.address }}</td>
  </tr>
</table>
  </div>
</template>

<script>
import Table from "../components/Table.vue";
export default {
  components: { Table },
  name: "IndexPage",
  data() {
    return {
      customers: [],
    };
  },
  props: {
    customer: {
      required: true,
      type: Object,
    },
  },
  async mounted() {
    const response = await this.$axios.$get("/api/customers");
    this.customers = response.data;
  },
};
</script>

if I write {{ customers }} the function return the list of customers fields but when I search for a specific data (for example {{ customers.name }}) it don't return me nothing, even errors.

Obviously I've set baseurl in nuxt.config with address of my laravel app

CodePudding user response:

Here you bring the data of all customers in the form of an array, If the data exists in the response, try using a v-for loop to iterate through the customers array and display the data for each customer. This would look something like this:

<template>
  <div>
     <table v-if="customers">
       <tr>
         <th>name</th>
         <th>address</th>
       </tr>
       <tr v-for="customer in customers" :key="customer.id">
         <td>{{ customer.name }}</td>
         <td>{{ customer.address }}</td>
       </tr>
     </table>
  </div>
</template>

CodePudding user response:

It looks like you are trying to access the name property of the customers array, but customers is an array of objects rather than a single object. You will need to loop through the customers array and display each customer's name and address in a separate table row.

Here is an example of how you can do this:

<template>
  <div>
    <table v-if="customers.length > 0">
      <tr>
        <th>name</th>
        <th>address</th>
      </tr>
      <tr v-for="customer in customers" :key="customer.id">
        <td>{{ customer.name }}</td>
        <td>{{ customer.address }}</td>
      </tr>
    </table>
  </div>
</template>

This will loop through the customers array and display a table row for each customer object. The v-for directive is used to loop through the array, and the :key attribute is used to give each table row a unique key. This is important for ensuring that Vue can keep track of each row when the array is updated.

I hope this helps! Let me know if you have any questions or if you need further assistance.

  • Related